The is
keyword in Python is used to check whether two variables point to the same object in memory, making it a comparison of object identity. This differs from the ==
operator, which compares whether two objects have the same value. By using is
, you can determine if two variables reference the exact same object.
is
Keyword WorksThe is
operator compares two variables to see if they refer to the same memory location. If they do, is
returns True
; otherwise, it returns False
.
This checks if a
and b
point to the same object.
In the example, a is b
returns True
because both variables refer to the same object in memory, while a is c
returns False
because c
is a different list object, even though its contents are identical.
is
and ==
**is**
: Compares the identity of two objects (whether they are the same object in memory).**==**
: Compares the values of two objects (whether their contents are the same).In this case, x == y
evaluates to True
because the contents of the lists are the same, but x is y
evaluates to False
because they are two distinct objects in memory. Meanwhile, x is z
is True
because z
refers to the same list as x
.
is
Keyword**None**
)One of the most common uses of the is
keyword is to check if a variable is None
, as None
is a singleton in Python (there is only one instance of it in memory).
Example:
This ensures that you're comparing the memory location of a
with the singleton None
, which is the correct way to check for None
in Python.
Python often reuses memory for small integers and strings to save space, so comparing these objects with is
might return True
even though they are separate variables.
Example:
This optimization is called "interning" and applies to certain immutable types like small integers and short strings.
The is
keyword in Python is used to compare the identity of two objects, checking if they occupy the same memory location. It's especially useful when working with singleton objects like None
or when you need to verify that two variables point to the same object. While is
checks object identity, the ==
operator checks value equality, making it essential to choose the right operator depending on your specific use case.