[issue45265] Bug in append() method in order to appending a temporary list to a empty list using for loop

Nima report at bugs.python.org
Wed Sep 22 14:01:40 EDT 2021


New submission from Nima <nim4fl at gmail.com>:

I want to make an list consist on subsequences of another list,
for example:
--------------------------------------------------------------
input: array = [4, 1, 8, 2]
output that i expect: [[4], [4,1], [4, 1, 8], [4, 1, 8, 2]]
--------------------------------------------------------------
but output is: [[4, 1, 8, 2], [4, 1, 8, 2], [4, 1, 8, 2],  [4, 1, 8, 2]]
--------------------------------------------------------------
my code is:

num = [4, 1, 8, 2]
temp = []
sub = []
for item in num:
    temp.append(item)
    sub.append(temp)
--------------------------------------------------------------
i think it's a bug because, append() must add an item to the end of the list, but here every time it add the temp to the sub it changes the previous item as well, so if it's not a bug please help me to write the correct code.

----------
components: Windows
messages: 402458
nosy: nima_fl, paul.moore, steve.dower, tim.golden, zach.ware
priority: normal
severity: normal
status: open
title: Bug in append() method in order to appending a temporary list to a empty list using for loop
type: behavior

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45265>
_______________________________________


More information about the Python-bugs-list mailing list