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?
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With