pythonlistappend

Python: append magic


list.append(x)

Add an item to the end of the list.

Okay. Let's write some code:

x = [[]]*3
x[0].append('foo')
print x

and output is:

[['foo'], ['foo'], ['foo']]

Why?


Solution

  • x = [[]]*3 Creates a list of length 3 where each element have the same reference. So appending to any element will give this result.