1

Code is as shown below :

s = [[]] *4
s[0].append(1)

print(s)

it gives me output :

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

but i want output like this :

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

How can i achieve that?

Mrugesh
  • 4,381
  • 8
  • 42
  • 84
  • 2
    Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – Chris Jun 21 '19 at 06:35
  • 1
    the reference remains the same so the operation on 1st row corresponds to all the row, create the 2D list using list comprehension as `[[] for _ in range(n)]` – arajshree Jun 21 '19 at 06:42

2 Answers2

6

You cannot use [[]] * 4 to create four lists. In this case, you are just creating one list and four references pointing to it.

So you should use [[] for _ in range(4)].

Sraw
  • 18,892
  • 11
  • 54
  • 87
1

Just an additional info to Sraw's reply:

>>> t = [[]] * 4 
>>> t
[[], [], [], []]
>>> id(t[0]) == id(t[1]) == id(t[2]) == id(t[3])
True
>>> l = [[], []]
>>> id(l[0]) == id(l[1])
False

You get 4 references to same list. That's why adding an element to any of the references show up in the others.

altunyurt
  • 2,821
  • 3
  • 38
  • 53