I was reading through the answer of Slicing a list in Python without generating a copy. The answer uses
>>> a = [1000 + 1, 1000 + 1, 1000 + 1]
>>> map(id, a)
[140502922988976, 140502922988952, 140502922988928]
to demonstrate that each integer gets a unique ID in a
.
As a sanity check, I ran the following code in my own environment (I'm on python3 so had to call list
on the map
)
> a = [1+1, 1+1, 1+1]
> list(map(id,a))
[140228695033632, 140228695033632, 140228695033632]
All I changed was the 1000
to 1
and now python assigns the same id to each number! I also ran the original code with 1000
, which gave three different IDs. Why is the behavior different for different sized integers?
I also wanted to play around with some other immutables.
Tuples always get different IDs.
> a = [(1,), (1,), (1,)]
> list(map(id,a))
[140228631126592, 140228631112728, 140228631128944]
Simple strings get the same ID.
> a = ['a', 'a', 'a']
> list(map(id,a))
[140068125361128, 140068125361128, 140068125361128]
Longer strings get different IDs.
> a = ['a'*1000, 'a'*1000, 'a'*1000]
> list(map(id,a))
[17589280, 17579408, 17580480]
I also investigated if it was something specific to lists:
> a, b = 1+1, 1+1
> a is b
True
> a, b = 1000+1, 1000+1
> a is b
False
What's going on here?