Consider the code below. Its output is
1 385712698864 385712698864
2 385744287024
3 385744287088
4 385712698864
5 385744286960
6 385744286960
7 385744286960
8 385712698864
This means that some of the operations in the code below change the id, but some do not, even though no operation changes the value of the variable a
:
- setting the variable to the value
"a"
always results in the same id (in this particular run, that was385712698864
) - using
a.lower()
changes the id ofa
after every call a[::-1]
changes the ida[:1]
does not change the idg(a)
does not change the idf(a)
changes the id
Can someone explain this seemingly inconsistent behaviour? (I am using python 3.8)
The code:
def f(x):
y = x + x
n = len(x)
return y[:n]
def g(x):
return "" + x
a = "a"
b = "a"
print(1, id(a), id(b))
a = a.lower()
print(2, id(a))
a = a.lower()
print(3, id(a))
a = "a"
print(4, id(a))
a = a[::-1]
print(5, id(a))
a = a[:1]
print(6, id(a))
a = g(a)
print(7, id(a))
a = f(a)
print(8, id(a))