Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
no tuple.copy()
#1
why is there no .copy() method for a tuple? but i can make a shallow copy using [:].
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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
>>> 
Skaperen likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Immutability is the reason for having a copy in the first place. How else are you going to produce an updated version?
Reply
#4
(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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
(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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020