0

Let say I wanted a list with all zeros of 5x3 (row x column). I can make the list in 2 ways

  1. Using for loop:
a = []   # My 2D list (currently empty)
for i in range(5):
    thisele = []
    for j in range(3):
        thisele.append(0)
    a.append(thisele)
  1. Using element multiplication method which I recently learnt
a = [[0]*3]*5

Now both genertes the same 2D list which looks like this

[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

Now I want to replace an element in the third column at first row with 11 so I used the following line a[0][2] = 11

This gives 2 different results based on the technique used. The first technique gives:

[0, 0, 11]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

and the second technique gives:

[0, 0, 11]
[0, 0, 11]
[0, 0, 11]
[0, 0, 11]
[0, 0, 11]

The second result is clearly undesirable as thats not what I intended to do. Can someone explain why the results vary in the second case and if it's a bug or a feature.

If its a feature then in what scenario can the second method be implemented

Prashant Kumar
  • 501
  • 8
  • 26

0 Answers0