A common misunderstanding about list.append() for newbies-----> like me

来源:互联网 发布:c语言中条件表达式 编辑:程序博客网 时间:2024/05/17 00:56

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


原创粉丝点击