Home > Mobile >  How do I create a "matrix" with a python list?
How do I create a "matrix" with a python list?

Time:08-12

I have a problem, where I can't use numpy and for the first time I stumbled across something odd in python.

Here is a minimal example:

a = [[0] * 3] * 3
print(a)
# will output [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
# as expected

a[1][1] = 1
# I expect : [[0, 0, 0], [0, 1, 0], [0, 0, 0]],
# but I get:

print(a)
# will output [[0, 1, 0], [0, 1, 0], [0, 1, 0]]
#                  ?                     ?

How can I create a list of lists, where all the elements are independent from each other?

And if someone bothers, could you explain, what happens there?

CodePudding user response:

What's happening here is that a reference to the same list (the one obtained from [0] * 3) is being placed 3 times in the new list, rather than 3 different lists being placed in it. A way to do what you want is:

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

CodePudding user response:

a = list()
n = 3
for i in range(n):
  a.append([0] * n)
  
a[1][1] = 1
print(a)
  • Related