0

I want to understand the difference between the following two ways of initializing a 2-dim list in python:

r1=2
c2=2

result = [[0] * r1] * c2

This makes a 2x2 list initialized with all zeros

and when I write:

result = [[0,0],[0,0]]

This also creates a 2-dim list initialized with zeros (is this true?)

Now when I insert values in the first case, like this:

r1=2
c2=2

result = [[0] * r1] * c2

for i in range(r1):
    for j in range(c2):
        result[i][j] = i+j
    print() 

print(result)

This does not insert the correct values, and rather the same values are repeated in both rows

However, when I insert values like this, in the second case:

r1=2
c2=2
result = [[0,0],[0,0]]

for i in range(r1):
    for j in range(c2):
        result[i][j] = i+j
    print() 

print(result)

This inserts the correct values.

What is the reason of wrong values insert in the former case and correct values in the latter case?

Thanks.

Osman Khalid
  • 778
  • 1
  • 7
  • 22
  • 1
    when working with python you don't need to "initialize" arrays/lists like in other languages. Just build them with the data you want. the initialization is done in the background. (just lamens for newer python programmers) – Jab Mar 23 '21 at 18:14
  • `[[0 for _ in range(m)] for _ in range(n)]` – wwii Mar 23 '21 at 18:18
  • @Jab do you mean appending everything? That is slower (even though not on this scale) – Yevhen Kuzmovych Mar 23 '21 at 18:26
  • @Jab. In this particular example, can I still use append? Will it give me the values at right indexes of two-dim array? – Osman Khalid Apr 04 '21 at 18:17

0 Answers0