5

I'm quiet confused to get this with python as below

>>> a = [[]]*3
>>> c=[[],[],[]]
>>> a
[[], [], []]
>>> c
[[], [], []]
>>> a == c
True
>>> a[1].append(2)
>>> a
[[2], [2], [2]]
>>> c[1].append(2)
>>> c
[[], [2], []]

I guess the reason is that in variable a, all three lists ponit to the same memory area until they are used in different ways. Is it right? Should I always be careful when doing initialization using things like * operator? THANKS!

LumiG
  • 452
  • 1
  • 6
  • 13
  • Also check this great answer for more info [about references](http://stackoverflow.com/a/986145/257972) – Mp0int Dec 25 '13 at 14:51

3 Answers3

6

To answer your question, let's look at the ids of the items in the lists:

>>> a = [[]]*3
>>> # The ids are the same
>>> id(a[0])
28340352
>>> id(a[1])
28340352
>>> id(a[2])
28340352
>>>

As you can see, a = [[]]*3 creates a list with three references to the same list object. Hence, modifying one will inevitably modify them all.

Regarding the other method:

>>> c=[[],[],[]]
>>> # The ids are different
>>> id(c[0])
28340632
>>> id(c[1])
28327248
>>> id(c[2])
28299216
>>>

As shown above, c=[[],[],[]] creates a list with three unique list objects. Meaning, you can modify one without modifying the others.

3

With a you are effectively creating a list and displaying the same list 3 times. Each of those 3 lists in a is like a reference to the same list in memory. So when you change any of the lists in a you change all of them, as they are the same list.

With c, you are creating 3 different lists explicitly. Changing one will not change the others. Hence the behaviour you are seeing.

Totem
  • 7,189
  • 5
  • 39
  • 66
2
>>> a = [ [ ] ]*3

The above code creates 3 lists inside one list. Note that you are not mentioning any limits to the lists inside the list. Here you are limiting the number of lists created inside to 3. So you can have 3 unbounded lists in that single list and each list inside will be identical if you use the append statements mentioned in the question.

>>> c=[ [ ],[ ],[ ] ] 

This code will create a list with three lists with each lists having one element inside it. The list outside have limit set to three and the ones inside have that set to one. Here you can append to the list by explicitly mentioning the location as in the question.

cutteeth
  • 2,148
  • 3
  • 25
  • 45