1

I wrote this code:

if __name__ == "__main__" :
    lst = []
    current= []
    for i in range(3):
        print(current)
        print(lst)
        lst.append(current)
        print(lst)
        current.append(i)

I expected it to print:

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

But instead it printed:

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

I don't understand why lst changes its members into current.

3 Answers3

3

instead of this line lst.append(current), Go with this:

from copy import copy

lst.append(copy(current))

This problem is that when you append current to the lst it looks fine, but in the next iteration when you change current and append it again, it will change the previous current that you already appended. that's why you see two [0] and three [0, 1]

take a look at This link for more clarification.

Also reading This Link will have positive effects of what is copy and types of copies.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0

unless you are doing a copy or deep copy, each element of lst will point at current

import copy
lst = []
current= []
for i in range(3):
        print(current)
        print(lst)
        lst.append(copy.copy(current))
        print(lst)
        current.append(i)

will print desired result

0

Shallow Copy

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

lst.append(current[:]) # shallow-copy

works in both Python 2 and 3.

lst = []
current= []
for i in range(3):
    print(current)
    print(lst)
    lst.append(current[:]) # shallow-copy
    print(lst)
    current.append(i)
ncica
  • 7,015
  • 1
  • 15
  • 37