-1

i was doing an assignment using Python and i had to use a 2D list with a specific size.

my idea was to use this..

lists = [[]]*10 //output => [[],[],[],[],[],[],[],[],[],[]]

because i have used..

nums = [0]*10 //output [0,0,0,0,0,0,0,0,0,0]

so far so good, the problem was wwhen i do this..

lists[0].append(5)     //the result is [[5],[5],[5],[5],[5],[5],[5],[5],[5],[5]]

it appends the object i'm adding to every list in lists, while if i did this..

nums[0] = 5   //the result is [5,0,0,0,0,0,0,0,0,0]

i have figured a work around the problem by using

lists = [[] for i in range(10)]

but my question is: why it did that, in first case?

Mahmoud Farouq
  • 423
  • 1
  • 3
  • 13

1 Answers1

-1

This is because when you declared lists = [[]]*10, you are instantiating a list of sublists that all point to the same list. Thus, when you append to the first item (or any item for that matter), it changes the original list, so all the lists that point to that also appear to change.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • i have got it **thanks man**. – Mahmoud Farouq Nov 24 '17 at 18:49
  • This is something to becareful about. Had you done `[[], []]`, you would have gotten `[[5], []]`. This is a similar caveat in Python to `def foo(bar=[])`. It's best to avoid these if you expect to mutate the internal values. – Serguei Fedorov Nov 24 '17 at 19:00