0

Possible Duplicate:
Unexpected feature in a Python list of lists
How to initialize a two-dimensional array in Python?

I wanted to create a nested list of nsize and then append items into it one by one according to a criterion.

For this I wrote it like following ( nsize = 4 )

a = [[]] * 4  # which creates on display a = [ [] , [] , [] , [] ]

Now I do something like this a[1].append(3) which gives me the output [[3], [3], [3], [3]]

What am I doing wrong here ? Should'nt only the 2nd list ( a[1] ) be updated with the value 3 ?

Community
  • 1
  • 1
anon
  • 342
  • 7
  • 22

2 Answers2

3

What you are doing creates a list with 4 references to the same sub-list.

You need to do something like a = [[] for _ in xrange(4)] instead.

Amber
  • 507,862
  • 82
  • 626
  • 550
0

Yes, it is supposed to work that way, even though it is often surprising. It is equivalent to this

b=[]
a=[b]*4

Then when you say a[1].append(3), that's just like saying b.append(3). And since a contains four references to that same list, you see it appear four times when you print a.

Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132