Append a value to a list and move all values over
if i st开发者_StackOverflow社区art off with :
a=[1,2,4]
and i want the result to be
a=[1,3,2,4]
how do i do this append?
In [18]: a=[1,2,4]
In [19]: a[1:1]=[3]
In [20]: a
Out[20]: [1, 3, 2, 4]
or
In [22]: a.insert(1,3)
In [24]: a
Out[24]: [1, 3, 2, 4]
With the first (slice) notation, you can even insert multiple elements (similar to extend
, but not necessarily at the end of the list):
In [26]: a[1:1]=[3,5]
In [27]: a
Out[27]: [1, 3, 5, 2, 4]
whereas with the insert
method, you can only insert one element:
In [30]: a.insert(1,[3,5])
In [31]: a
Out[31]: [1, [3, 5], 2, 4]
The slice notation can also be used to modify or remove parts of a list.
a.insert( 1, 3 )
You can do this with the slice operator:
a[1:1] = (3,)
Or with the insert function:
a.insert(1, 3)
In both cases, position 1
refers to the second slot in the list.
精彩评论