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?
In
li2 = [['a']] * 3you create one list with three list elements but these lists are actually the same object. That means: when you modifyli2[0], you also modifyli2[1]andli2[2].The following line actually creates a list with three different list objects inside it:
In this case, when you modify
li1[0]you only modify that list. The other lists are unaffected. This explains why you are getting different lists inli1andli2.