1

When I assign an integer to a variable its id() is still the same no matter how many times I refreshed the code. However, string and tuple, x and z, respectively, are changing, what's really happening under the hood?

x = '100'
y = 100
z = (100,)

print('string:', id(x))  # changing
print('integer:', id(y))  # constant
print('tuple:', id(z))  # changing


##########################################################################
# INITIAL
# string: 47850176
# integer: 1804263136
# tuple: 47679056
#
# REFRESH
# string: 15409856
# integer: 1804263136
# tuple: 15238736
##########################################################################

1 Answers1

0

In python, small integer are predefined constant values (for performance reasons).

>>> x = 10
>>> x is 10
True
>>> x = 123456
>>> x is 123456
False

(as an exercise, you may put this in a for loop to find the bounds).

Demi-Lune
  • 1,868
  • 2
  • 15
  • 26