Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python issue with for loop and append [duplicate]

I'm having trouble understanding the output of a piece of python code.

mani=[]
nima=[]
for i in range(3)
    nima.append(i)
    mani.append(nima)

print(mani)

The output is

[[0,1,2], [0,1,2], [0,1,2]] 

I can't for the life of me understand why it is not

[[0], [0,1], [0,1,2]]

Any help much appreciated.

like image 497
r3za Avatar asked Jun 20 '20 14:06

r3za


Video Answer


3 Answers

It's because when you append nima into mani, it isn't a copy of nima, but a reference to nima.

So as nima changes, the reference at each location in mani, just points to the changed nima.

Since nima ends up as [0, 1, 2], then each reference appended into mani, just refers to the same object.

like image 104
PETER STACEY Avatar answered Oct 23 '22 07:10

PETER STACEY


Just to complete as some have suggested, you should use the copy module. Your code would look like:

import copy

mani=[]
nima=[]
for i in range(3):
    nima.append(i)
    mani.append(copy.copy(nima))

print(mani)

Output:

[[0], [0, 1], [0, 1, 2]]
like image 34
Tomás Denis Reyes Sánchez Avatar answered Oct 23 '22 09:10

Tomás Denis Reyes Sánchez


List are mutable (mutable sequences can be changed after they are created), you can see that you are operating on the same object using id function:

for i in mani:
    print(id(i))
like image 31
dejanualex Avatar answered Oct 23 '22 07:10

dejanualex