How does the Python identity operator work?

Asked

Viewed 35 times

3

I’m starting in Python and would like to ask a question based on the code below:

Case 1

x = 5
y = 5

print(x is y) # retorna True

Case 2

x = "carro"
y = "carro"

print(x is y) # retorna True

Case 3:

x = [1,2,3]
y = [1,2,3]

print(x is y) # retorna False

Why does this happen? I have already researched this subject and know the identity operator is compares objects and their memory location and not their values - what is done by the operator ==.

But even so, I don’t understand for example why integers and strings are allocated or pointed to the same memory location and lists not for some internal Python reason, if that is indeed true.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.