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.
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.
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]]
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With