2

I have this code:

lst = []
given = [1, 2, 3, 4, 5]
result = []

for item in given:
    lst.append(item)
    print(lst)
    result.append(lst)

print(result)

My expected result is [[1], [1, 2], [1, 2, 3], ...], but displayed result is [[1, 2, 3, 4, 5], ...] with 12345 repeated 5 times. What is wrong?

lst printed is as expected, which is [1] for the first loop, [1, 2] for the second loop, and so on.

Eb946207
  • 748
  • 8
  • 26
Leo
  • 21
  • 1

4 Answers4

3

Python doesn't create copy of lst every time when you append it to result, it just inserts reference. As a result you get list with N references to same list.

To create a copy of lst you can use lst.copy(). Also list slice operator works same lst[:].

Shortened version of your code:

given = [1, 2, 3, 4, 5]
result = [given[0 : i + 1] for i in range(len(given))]
print(result)

Result:

[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
1

The problem is that you are appending the list as such which is equivalent to appending the reference object to the original list. Therefore, whenever the original list is modified, the changes are reflected in the places where the reference is created, in this case in result. As you keep iterating via the for loop, all your references appended in result keep getting updated with the latest value of lst. The final result is that at the end of the for loop, you have appended 5 references to the original list lst and all of them store the latest value of lst being [1,2,3,4,5].

There are several ways to avoid this. What you need is to copy only the values. One of them is to use lst[:]. other way is to use lst.copy()

for item in given:
    lst.append(item)
    print(lst)
    result.append(lst[:])

print (result)
# [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
Sheldore
  • 37,862
  • 7
  • 57
  • 71
1

List is a mutable data type, there is only one copy in memory for a list unless you explicitly copy it to another variable. So

result.append(lst)

just appends a reference of the real copy and all the refercences point to the same copy.

In conclusion, you should learn about mutable/immutable data types and reference count in python.

limen
  • 67
  • 7
0

Append lst.copy() gives the right output.

lst = []
given = [1,2,3,4,5]
result = []

for item in given:
    lst.append(item)
    print(lst)
    result.append(lst.copy())

print(result)
Ha Bom
  • 2,787
  • 3
  • 15
  • 29