What is the difference between "==" and "is" in Python?

Asked

Viewed 280 times

5

Using the two lists below as an example:

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

And testing:

x == y
x is y

The first test gives True and the second gives False. Why the result is different in both cases?

  • Greetings Thiago. I would recommend a little more caution when creating a question here on the site, because the system has automatic penalties for users with many closed questions. What I usually recommend doing before asking is to access the chat and discuss with staff about the possible question; if it is duplicated probably someone will already know how to indicate. I am always online there and will help in the possible, especially in Python. Just try not to be penalized for something simple even if you have the best intentions.

1 answer

5


== compares whether variables have the same value. is checks whether both refer to the same object or not.

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

x == y (true)
x is y (false)

x and y have the same value [1, 2], but they are different objects.

  • Just need to complete saying because in this case are equal but are different objects, because this does not always happen. If x = 2 and y = 2, x is y will be True, different from the example of the question.

Browser other questions tagged

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