0

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?

Community
  • 1
  • 1
Sergei G
  • 1,550
  • 3
  • 24
  • 44

2 Answers2

5

In li2 = [['a']] * 3 you create one list with three list elements but these lists are actually the same object. That means: when you modify li2[0], you also modify li2[1] and li2[2].

The following line actually creates a list with three different list objects inside it:

li1 = [['a'], ['a'], ['a']]

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 in li1 and li2.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
1

check the value of id() for each element,which clearly suggest the reason of their behavior.

>>> li1 = [['a'], ['a'], ['a']]
>>> for x in li1:                  #different id()
    id(x)


145497484
145514156
145511500

Same values of id():

>>> li1=['a']*3
>>> for x in li1:
    print id(x)


3078093024
3078093024
3078093024
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504