Mailing List Archive

[issue45265] Bug in append() method in order to appending a temporary list to a empty list using for loop
New submission from Nima <nim4fl@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@bugs.python.org>
<https://bugs.python.org/issue45265>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/list-python-bugs%40lists.gossamer-threads.com
[issue45265] Bug in append() method in order to appending a temporary list to a empty list using for loop [ In reply to ]
Raymond Hettinger <raymond.hettinger@gmail.com> added the comment:

This is expected behavior.

To get a better understanding, see: https://docs.python.org/3/faq/programming.html#why-did-changing-list-y-also-change-list-x

To get help writing correct code, please do not use the bug tracker. Consider posting to StackOverflow instead.

----------
nosy: +rhettinger
resolution: -> not a bug
stage: -> resolved
status: open -> closed

_______________________________________
Python tracker <report@bugs.python.org>
<https://bugs.python.org/issue45265>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/list-python-bugs%40lists.gossamer-threads.com