0

I have a question regarding 2d lists in python after initilizing the list when I assign a value to an index of list I will get all the indexes assigned with the value I'm really confused can someone explain why this is happening also how should I fix this issue

class_list = [[0] * 3] * 10
print(class_list)

class_list[2][1]  = 10
print(class_list)

and this is result:

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

Sib
  • 1

2 Answers2

0

Numpy

import numpy as np

class_list = np.array([[0] * 3]*10) 
print(class_list)

class_list[2][1]  = 10
# class_list.tolist() # if you want to use lists only.
print(class_list)

You will get the expected output.

ombk
  • 2,036
  • 1
  • 4
  • 16
0

np.zeros

import numpy as np

class_list = np.zeros((10, 3))
class_list[2][1]  = 10
WhySoSerious
  • 185
  • 1
  • 19