[issue21943] To duplicate a list has biyective properties, not inyective ones
Josh Rosenberg
report at bugs.python.org
Wed Jul 9 12:22:59 CEST 2014
Josh Rosenberg added the comment:
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.
----------
nosy: +josh.rosenberg
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue21943>
_______________________________________
More information about the Python-bugs-list
mailing list