-1

I am trying to make a list of 5 lists.

I did that by web = [[]]*5

Now I want to update the first list in the 'list of lists' with values 1 and 2.

web[0].append(1)
web[0].append(2)

But my output is

[[1, 2],
[1, 2],
[1, 2],
[1, 2],
[1, 2],
[1, 2],
[1, 2],
[1, 2],
[1, 2],
[1, 2]]

But shouldn't the first list be updated only? My desired output is as below

[[1, 2],
[],
[],
[],
[],
[],
[],
[],
[],
[]]
Kevin George
  • 119
  • 2
  • 13

2 Answers2

4

When you create web = [[]]*5, you are actually creating an array of references to the same object (a list of []s). So when you change the object via one reference, this changes all entries in the list.

This is a very common Python 'gotcha' for beginners.

try this instead:

web = [[] for x in xrange(5)]
Alex Fung
  • 1,996
  • 13
  • 21
  • can you point me to a references for more explanation of this – Reynard Asis Feb 28 '17 at 06:24
  • @ReynardAsis check out [here](http://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Alex Fung Feb 28 '17 at 06:25
  • Instead of answering a "common Python 'gotcha'" and linking to the canonical page for it, you can flag the question for closure as a duplicate. This reduces fragmentation and makes the site easier to use. – TigerhawkT3 Feb 28 '17 at 06:27
-3

Creating list that way, creates duplicates only.You can rather creating this way:

n = 5 #range
web = [[] for _ in range(n)]

web[0].append(1)
web[0].append(2)
print(web)

Ouput:

[
 [1, 2],
 [],
 [],
 [],
 []
]
Taufiq Rahman
  • 5,600
  • 2
  • 36
  • 44