Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a bidimensional array in Python [duplicate]

I was building a bidimensional vector in Python, and since I wanted it to be all zero at first, and didn't wanted to use numpy, I tried this:

columns = 8
rows = 5
m = [[0]* (columns)] * (rows)
m[3][2] = 1
print m

And I got an unexpected behaviour:

>> [[0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0]]

It looks like building the bidimensional array like this, makes each row a reference to a single row, so if writting in any of them, you are writing over all of them.

Maybe this sounds evident to some of you, but I got a little socked. Of course I can fix it using a different approach, but I am curious of why this is happening.

Can anyone explain? Why is this not happening if you build a simple array with [0] * size_of_array?

like image 958
Roman Rdgz Avatar asked Feb 16 '23 01:02

Roman Rdgz


1 Answers

This is a common Python gothca. You are not creating rows inner lists, you're creating rows references to the same list.

Your code is equivalent to the following:

inner_list = [0] * columns
m = [inner_list] * rows

I would recommend building the rows without using the * operator. (You don't run into the issue with columns, since 0 is an int and ints are immutable objects.)

matrix = []
for row in rows:
    matrix.append([0] * columns)
like image 200
HardlyKnowEm Avatar answered Feb 18 '23 14:02

HardlyKnowEm