0

Possible Duplicate:
Unexpected feature in a Python list of lists
Python list confusion

Consider the following code:

a = [[]] * 3
a[1].append("foo")

I would expect the value of a to become:

[[], ["foo"], []]

instead, every element of a is updated:

[["foo"], ["foo"], ["foo"]]

Can someone please explain why did each element of the list got updated instead of just the defined element (a[1])? Is there something fundamentally wrong in my logic?

For what it's worth I'm running Python2.7

Community
  • 1
  • 1
rahmu
  • 5,708
  • 9
  • 39
  • 57
  • 3
    This has been asked thousands of times.. Lemme find a duplicate :) – Niklas B. Apr 21 '12 at 14:28
  • Thanks. It's difficult to find a proper title to this question, so I couldn't find a duplicate easily. Thanks for pointing it out :) – rahmu Apr 21 '12 at 14:30
  • @rahmu: Yep, I know, it's unfortunate, but it's sure not your fault :) Have fun. – Niklas B. Apr 21 '12 at 14:30
  • Yeah, it was pointed out before that you can't search for this problem unless you know what it is. – jamylak Apr 21 '12 at 14:31
  • 3
    @rahmu: Symbolhound is however quite good at finding small code snippets: [Search results for `[[]] * ` on Stackoverflow](http://symbolhound.com/?q=python&l=&e=%5B%5B%5D%5D+*&n=&u=stackoverflow.com) The third result is already a duplicate. – Niklas B. Apr 21 '12 at 14:32

2 Answers2

1

Lists in Python are objects, this means when you assign a list to another variable, changing either will change the actual list, for example

a = []
b = a
b.append("hi")
print a
// a is now ["hi"]

When you do the assignment

a = [[]] * 3

It's the same as saying

inner_list = []
outer_list = [inner_list, inner_list, inner_list]

In other words, all the inner lists are the same object. Not different objects as you think.

To get the effect you want, you should do:

outer_list = []
for i in range(0, 3):
    outer_list.append([])

Which creates a 3 inner lists objects and puts the into the outer object.

Hampus Nilsson
  • 6,692
  • 1
  • 25
  • 29
0

I think you'll find what is happening is that what python is doing is creating:

outer_list = []
inner_list = []
outer_list = [inner_list,inner_list,inner_list]

or to explain it more clearly, outer_list and inner list are created once, and then inner_list is copied * 3 into outer_list, which means all 3 lists in the outer_list are actually a reference to the same inner_list copied 3 times.

Serdalis
  • 10,296
  • 2
  • 38
  • 58