Python 3.7.4 (default, Sep 8 2020, 19:45:30) [GCC 7.5.0] on linux
first_tuple = (1, 2, )
second_tuple = (1, 2, )
first_list = [1, 2, 3]
second_list = [1, 2, 3]
def main():
# Question 1
my_dict = {
first_tuple: first_list,
second_tuple: second_list,
}
print('dictionary length = {}'.format(len(my_dict)))
for key in my_dict.keys():
if id(key) == id(second_tuple):
print("key selected is 'second_tuple'")
else:
print("key selected is 'first_tuple'")
if id(my_dict[key]) == id(second_list):
print("value selected is 'second_list'")
else:
print("key selected is 'first_list'")
# Question 2`
my_set = {first_tuple, second_tuple}
print('set length = {}'.format(len(my_set)))
if id(my_set.pop()) == id(second_tuple):
print("'second_tuple' is considered")
else:
print("'first_tuple' is considered")
main()
Above snippet when executed in a python shell is giving output as:
dictionary length = 1
key selected is 'first_tuple'
value selected is 'second_list'
set length = 1
'first_tuple' is considered
And when same is executed as a script eg. python3.7 example.py
dictionary length = 1
key selected is 'second_tuple'
value selected is 'second_list'
set length = 1
'second_tuple' is considered
Why there is a difference? Is compiler doing some optimisation?
CodePudding user response:
Yes, it's a compiler optimization. The same tuple is being used for first_tuple
and second_tuple
when the script is compiled. This is allowed because tuples are immutable, so there's no need to distinguish between equal tuples.
You can see this with a much simpler example:
first_tuple = (1, 2, )
second_tuple = (1, 2, )
print(first_tuple is second_tuple)
This prints True
in a script, but False
in the shell.