0

Possible Duplicate:
Python list confusion

When I write a simple python script, I define a new list as follows:

A=[[],]*10

What I wanna do is just initialize a list whose length is 10 and each element is a empty list.

And when I do something like:

A[0].append(["abc",])

I just wanna append this ["abc",] to A[0], and it turn out to be that every elements in A is appended with ["abc",]

I know this probably due to my initialization (A=[[],]*10) . I just want to know why this happened.

Community
  • 1
  • 1
Jerry Meng
  • 1,466
  • 3
  • 21
  • 40
  • `[x,]` likely is better written as `[x]`. In any case, note that `list*int` does *not* clone objects. –  Sep 22 '12 at 21:08

3 Answers3

3

Your expression A=[[]]*10 is equivalent to:

a = []
A = [a]*10

This means that A consists of 10 references to one and the same list.

Vortexfive
  • 1,889
  • 13
  • 19
2

You are creating a list with 10 references to the same empty list.

You should use a list comprehension instead:

A = [[] for _ in range(10)]

In a list comprehension, you create a new list for every iteration through the loop. If you are using python 2, you should use xrange instead of range (although with only 10 elements that won't make much difference).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

All the empty lists are references to the same object.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94