9

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.

r3za
  • 93
  • 3

3 Answers3

6

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.

PETER STACEY
  • 213
  • 2
  • 9
  • 2
    Because a List is mutable it can be changed after it is created. :) – EdKenbers Jun 20 '20 at 14:35
  • Aha, and there it is, the hole in my understanding. I mainly used matlab in the past, and if i remember correctly it worked with the copy, as oppose to reference in such a situation (i think anyway!). Many thanks. – r3za Jun 20 '20 at 15:08
5

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]]
1

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))
dejanualex
  • 3,872
  • 6
  • 22
  • 37