-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],
[],
[],
[],
[],
[],
[],
[],
[],
[]]
0

2 Answers 2

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)]
Sign up to request clarification or add additional context in comments.

3 Comments

can you point me to a references for more explanation of this
@ReynardAsis check out here
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.
-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],
 [],
 [],
 [],
 []
]

2 Comments

He's duplicating the same array which is because of how he is trying to initialize the array, so any append to one of the lists will append to them all, because they are the same object.
You are right. I edited my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.