Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Even though tuples are immutable, they are stored in different addresses in interactive mode. Why?

t = (1,2,3)
t1 = (1,2,3)
print(id(t))
print(id(t1))

The above lines of code gives the same addresses in script mode in Python, but in interactive mode it outputs different addresses. Can anyone explain the reason for this?

like image 350
Harsha jk Avatar asked Jun 11 '20 15:06

Harsha jk


People also ask

Why are tuples said to be immutable?

Tuples and lists are the same in every way except two: tuples use parentheses instead of square brackets, and the items in tuples cannot be modified (but the items in lists can be modified). We often call lists mutable (meaning they can be changed) and tuples immutable (meaning they cannot be changed).

Is tuple mutable or immutable explain why?

A tuple is a sequence of values much like a list. The values stored in a tuple can be any type, and they are indexed by integers. The important difference is that tuples are immutable. Tuples are also comparable and hashable so we can sort lists of them and use tuples as key values in Python dictionaries.

Why can tuples contain mutable items?

That's because tuples don't contain lists, strings or numbers. They contain references to other objects. The inability to change the sequence of references a tuple contains doesn't mean that you can't mutate the objects associated with those references.

Are tuples just immutable lists?

The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that tuples cannot be changed while the lists can be modified. Tuples are more memory efficient than the lists.


1 Answers

When the script is being compiled, the compiler can search for all the equivalent tuples and generate code to use the same reference for all of them.

But in interactive mode, it would need to keep a cache of all tuples so it could search for a previous equivalent tuple and return a reference to it, rather than creating a new tuple each time. The interactive interpreter doesn't do this.

If you assign both variables on the same line, you actually get the same tuple.

t = (1, 2, 3); t1 = (1, 2, 3)

This is presumably because it's running the compiler for each input, so it can do the full analysis and optimization.

like image 160
Barmar Avatar answered Sep 30 '22 19:09

Barmar