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

cannot understand why these two codes dont have the same output

input1 :

for i in range(5):
    lst = [0,0,0,0,0]
    lst[i] = 1
    print(lst)

output1 :

1, 0, 0, 0, 0
0, 1, 0, 0, 0
0, 0, 1, 0, 0
0, 0, 0, 1, 0
0, 0, 0, 0, 1

input2 :

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

mainlst = [0,0,0,0,0]
for i in range(5):
    templst = mainlst
    templst[i] = 1
    print(templst)

output2 :

1, 0, 0, 0, 0
1, 1, 0, 0, 0
1, 1, 1, 0, 0
1, 1, 1, 1, 0
1, 1, 1, 1, 1

Why does assigning a value, to a variable, 1) as a list, and 2) as a variable(whose value is the same as the list), not have the same output
i expected the two to give the same output

>Solution :

In the second example you’re referencing the mainlst every time. If you change your code to:

mainlst = [0,0,0,0,0]
for i in range(5):
    templst = mainlst.copy()
    templst[i] = 1
    print(templst)

You’ll get the same results. Look up more about python arrays and deep vs shallow copies.

https://realpython.com/copying-python-objects/

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