appending to a nested list in python [duplicate]

雨燕双飞 提交于 2020-01-05 05:38:25

问题


Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
Python - Using the Multiply Operator to Create Copies of Objects in Lists

Python behaves unexpected when i append to a list, which is in another list. Here's an example:

>>> _list = [[]] * 7
>>> _list
[[], [], [], [], [], [], []]
>>> _list[0].append("value")

What i expect:

>>> _list
[['value'], [], [], [], [], [], []]

What i get:

>>> _list
[['value'], ['value'], ['value'], ['value'], ['value'], ['value'], ['value']]

Why is this? how can i go around it?


回答1:


Your problem is that your list does not contain seven independent lists, but rather the same list seven times.

To create a list of list, better use a list comprehension:

_list = [[] for _ in xrange(7)]

which will result in a list containing seven different lists.



来源:https://stackoverflow.com/questions/13763157/appending-to-a-nested-list-in-python

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