This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: list illogical affectation
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.6, Python 3.2, Python 3.3, Python 3.4, Python 3.5, Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: SilentGhost, abarry, antoine Zellmeyer, ned.deily, ronaldoussoren, terry.reedy
Priority: normal Keywords:

Created on 2016-08-02 12:09 by antoine Zellmeyer, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (3)
msg271817 - (view) Author: antoine Zellmeyer (antoine Zellmeyer) Date: 2016-08-02 12:09
>>> tab = [['x']*3]*3
>>> tab
[['x', 'x', 'x'], ['x', 'x', 'x'], ['x', 'x', 'x']]
>>> tab[1][0] = 5
>>> tab
[[5, 'x', 'x'], [5, 'x', 'x'], [5, 'x', 'x']]
>>> 

why not only the element tab[1][0] is changed ?
msg271818 - (view) Author: SilentGhost (SilentGhost) * (Python triager) Date: 2016-08-02 12:19
Because elements of the tab list are the same list. And since list is a mutable type, modifying list object will be visible to via all the reference / names that point to that object. There are various ways to work around this behaviour, typically a list comprehension is used.

P.S. Please don't add spurious components to the issue, it adds people to the nosy list.
msg271819 - (view) Author: Anilyka Barry (abarry) * (Python triager) Date: 2016-08-02 12:21
To add to what SilentGhost just said; the '*' operator for lists doesn't create new lists, but simply creates new references to the same list (i.e. it doesn't re-evaluate the expression).

To create separate lists, you can do a list comprehension such as:

[['x'] * 3 for _ in range(3)]

More information is available on the FAQ: https://docs.python.org/3/faq/programming.html#why-did-changing-list-y-also-change-list-x
History
Date User Action Args
2022-04-11 14:58:34adminsetgithub: 71855
2016-08-02 12:21:28abarrysetassignee: terry.reedy ->

messages: + msg271819
nosy: + abarry
2016-08-02 12:19:26SilentGhostsetstatus: open -> closed

components: - IDLE, macOS

nosy: + SilentGhost
messages: + msg271818
resolution: not a bug
stage: resolved
2016-08-02 12:09:18antoine Zellmeyercreate