1

I,m new in python and have a code like this in python 3.9:

a = [[0]*3]*3
a[0][0] = 1
print(a)

output: [[1,0,0],[1,0,0],[1,0,0]]

I thought that the output should be:

output: [[1,0,0],[0,0,0],[0,0,0]]

changing this line

a = [[0]*3]*3

to

a=[]
for i in range(3):
   a.append([0]*3)

will solve the issue

could someone tell me where I am wrong please.

Hadelo
  • 53
  • 7
  • Using an expression like this `[A]*B` creates a list with `B` items in it, but all items point to the same object so changing any element inside any of these items will be reflected on the rest so to avoid that you need to try doing something like this: a = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] a[0][0] = 1 print(a) – Hamzah Zabin Feb 22 '22 at 08:18

1 Answers1

-1

That is because when using a = [[0]*3]*3, you are creating 3 references to the created [0]*3 element, hence when you change one of them, all of them change together.

Solution 1

a = [[0 for _ in range(3)] for _ in range(3)]

This solution utilizes list comprehension, avoiding unnecessary lines and messy code.

Solution 2

a = []
for _ in range(3):
  row = []
  for _ in range(3):
    row.append(0)
  a.append(row)

This solution utilizes traditional for loops. It may be easier to understand for someone with less Python background.

Solution 3 (Recommended)

import numpy

a = numpy.zeros((3, 3))
a[0,0] = 1

This solution uses numpy, which is a python mathematical package that allows for easy manipulation of values and matrices. It in general makes working with 2-dimensional arrays filled with numbers much easier.

Joshuc
  • 1
  • 1
  • 3