Python Forum
no tuple.copy() - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: no tuple.copy() (/thread-37087.html)



no tuple.copy() - Skaperen - Apr-30-2022

why is there no .copy() method for a tuple? but i can make a shallow copy using [:].


RE: no tuple.copy() - buran - May-04-2022

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
>>> 



RE: no tuple.copy() - ndc85430 - May-04-2022

Immutability is the reason for having a copy in the first place. How else are you going to produce an updated version?


RE: no tuple.copy() - buran - May-04-2022

(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.


RE: no tuple.copy() - Skaperen - May-04-2022

(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?