简体   繁体   中英

What happens to the new Python Tuple when it is added to itself

I have a beginner question on Python. If I have a python tuple:

x = ('a', 'b', 'c')

and then x + x would give me:

('a', 'b', 'c', 'a', 'b', 'c')

Question:

What happens to the new Python Tuple when it is added to itself x + x ? I can reference the tuple x but what about the new tuple that is x + x , how would you reference? Does it become a unreferenced memory, meaning no pointer can reference it?

Thank you,

G.

tuples are immutable. tuple.__add__ (which is called when you add tuples) will return an entirely new tuple object with content of both tuples in it. To reference it later you have to store the reference in a variable:

new_tuple = x + x
print(new_tuple)

If you don't store the reference, it becomes "unreferenced" as you say in the question, and then the python garbage collector will destroy it and free the memory automatically. The same happens to any python object when the number of references to it reaches zero.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM