Problem concatenating Python list

拟墨画扇 提交于 2019-12-06 11:00:51

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]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!