Python Forum

Full Version: no tuple.copy()
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
why is there no .copy() method for a tuple? but i can make a shallow copy using [:].
it's immutable. why would you need a copy? Reference is good enough.
there is no e.g. str.copy either :-)

Note that with [:] it's the same object (same id), not a copy

Python 3.9.4 (default, Apr  9 2021, 01:15:05) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> spam = (1, 2, 3)
>>> eggs = spam[:]
>>> id(spam)
139751983214912
>>> id(eggs)
139751983214912
>>> 
Immutability is the reason for having a copy in the first place. How else are you going to produce an updated version?
(May-04-2022, 05:31 AM)ndc85430 Wrote: [ -> ]Immutability is the reason for having a copy in the first place. How else are you going to produce an updated version?
Creating a copy of immutable object will create new immutable object identical to the original one (that is assuming there are indeed 2 objects with different ids), which you will not be able to modify anyway - hence there is no need to keep 2 identical immutable objects in memory. As I show, creating a new "copy" via slicing is in fact just new reference to the same object. You suggest that at some point during the creation of a copy, the new object will be mutable.
Depending on what means "updated" version there would be different approaches, e.g. comprehension. But copy method definitely will not do.
(May-04-2022, 05:31 AM)ndc85430 Wrote: [ -> ]Immutability is the reason for having a copy in the first place. How else are you going to produce an updated version?

the copy will also be immutable. how are you going to update it?