Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
Python list confusion
I am a bit puzzled with lists of lists in Python. I have these two snippets:
li1 = [['a'], ['a'], ['a']]
print li1
for i in range(0, len(li1)):
li1[i] += [i]
print li1
li2 = [['a']] * 3
print li2
for i in range(0, len(li2)):
li2[i] += [i]
print li2
After creation li1 and li2 are the same, but when I add elements they behave differently:
[['a'], ['a'], ['a']]
[['a', 0], ['a', 1], ['a', 2]]
[['a'], ['a'], ['a']]
[['a', 0, 1, 2], ['a', 0, 1, 2], ['a', 0, 1, 2]]
Could some one please explain where the trick is?