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: To duplicate a list has biyective properties, not inyective ones
Type: behavior Stage:
Components: Demos and Tools Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Toni Diaz, josh.r
Priority: normal Keywords:

Created on 2014-07-09 09:11 by Toni Diaz, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (3)
msg222606 - (view) Author: Toni Diaz (Toni Diaz) Date: 2014-07-09 09:11
Python 2.7.3 (default, Mar 13 2014, 11:03:55) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a=['dog']
>>> b=a
>>> a
['dog']
>>> b
['dog']
>>> b.remove('dog')
>>> a
[]
>>> b
[]
>>>

When defining a list from another (b=a), in my opinion, I expect that all you do to one doesn't affect to the other one.
However, with the commands .remove & .append I don't see that (the definition b=a is bijective).
Should it work this way?

Thanks
msg222607 - (view) Author: Josh Rosenberg (josh.r) * (Python triager) Date: 2014-07-09 10:22
This is a natural consequence of Python using reference semantics.

x = y

just makes x and y references to the same object. For immutable objects like int and str, you'll never notice consequences of this, since changes to the value (x += 1) replace the reference in x with a new reference. But for mutable objects like lists, you need to explicitly copy (shallow or deep) to avoid a dependency of the sort you've encountered.

For the specific case of sequences, the empty slice is the simplest, fastest way to perform a shallow copy:

x = y[:]

For other built-in types, you can often call .copy() or wrap in the constructor:

newdict = olddict.copy() # or dict(olddict)

For more complex cases, the copy module offers shallow and deep copy abilities (via the copy and deepcopy function) for arbitrary data structures.
msg222608 - (view) Author: Josh Rosenberg (josh.r) * (Python triager) Date: 2014-07-09 10:25
Short answer: This is not a bug. Run through one of the comprehensive Python tutorials on the net (or in Learning Python); reference semantics and their fairly varied consequences are covered in detail in most of them.
History
Date User Action Args
2022-04-11 14:58:05adminsetgithub: 66142
2014-07-09 10:47:05mark.dickinsonsetstatus: open -> closed
resolution: not a bug
2014-07-09 10:25:32josh.rsetmessages: + msg222608
2014-07-09 10:22:59josh.rsetnosy: + josh.r
messages: + msg222607
2014-07-09 09:11:52Toni Diazcreate