Well,list.append() is to append an element to the end of a list
However, if this element is a list too, append() will not copy this list to the newly generated list, but simply makes a reference to this list.
So, any change to this list will also change the generated one, and vice versa.
A simple test:
>>> a = ['test']*3
>>> b = []
>>> b.append(a)
>>> b.append(a)
>>> print(b)
[['test', 'test', 'test'], ['test', 'test', 'test']]
>>> b[0][0] = 1
>>> print(b)
[[1, 'test', 'test'], [1, 'test', 'test']]
>>> print(a)
[1, 'test', 'test']
And two more issues about this 'bug'
Case 1: http://bugs.python.org/issue8023
Case 2: http://mail.python.org/pipermail/python-bugs-list/2007-February/037113.html
本文探讨了Python中使用list.append()方法时的一个常见误区:当添加的元素为列表时,并非复制该列表,而是创建指向同一列表的引用。这会导致原始列表和目标列表间的数据同步变化。文章通过实例演示了这一现象,并提供了两个相关案例链接。
1554

被折叠的 条评论
为什么被折叠?



