Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python list manipulation differs based on initialization

I want to have square matrix of integers with dimensions 3×3. I don’t want to use numpy. There are several ways how to initialize such structure. For example:

Direct definition (explicitly written out the whole structure):

a = [ [0,0,0], [0,0,0], [0,0,0] ]

and

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

b = [[0]*3]*3

When I type ‘a’ or ‘b’ in python3 interpreter I got same results (str function for both objects prints out the same):

>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> b
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

however, when I try to set for example number on position row, column = 0, 1 I get different results:

>>> a[0][1] = 1
>>> b[0][1] = 1
>>> a
[[0, 1, 0], [0, 0, 0], [0, 0, 0]]
>>> b
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]

How so? What’s special about [[0]*3]*3?

>Solution :

The second one creates three rows that are addressing the same memory. This way any change in one of them reflects to them all. The first one, on the other side, creates three separate lists

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading