Problem concatenating Python list
I am trying to concatenate two lists, one with just one element, by doing this:
开发者_如何学Pythonprint([6].append([1,1,0,0,0]))
However, Python returns None
. What am I doing wrong?
Use the + operator
>>> [6] + [1,1,0,0,0]
[6, 1, 1, 0, 0, 0]
What you were attempting to do, is append a list onto another list, which would result in
>>> [6].append([1,1,0,0,0])
[6, [1,1,0,0,0]]
Why you are seeing None
returned, is because .append
is destructive, modifying the original list, and returning None
. It does not return the list that you're appending to. So your list is being modified, but you're printing the output of the function .append
.
For list concatenation you have two options:
newlist = list1 + list2
list1.extend(list2)
use a list first (unless you really do not want to use your data in future )
>>> a=[6]
>>> a.append([1,1,0,0,0])
>>> a
[6, [1, 1, 0, 0, 0]]
another way is to use extend()
instead of append()
>>> a=[6]
>>> a.extend([1,1,0,0,0])
>>> a
[6, 1, 1, 0, 0, 0]
l1 = [6]
l2 = [1, 1, 0, 0, 0]
l1.extend(l2)
print l1
[6, 1, 1, 0, 0, 0]
精彩评论