is
In Python, the is
keyword lets you test for object identity. Unlike the equality operator ==
, which checks if the values of two objects are the same, is
checks whether two variables point to the same object in memory. This distinction is crucial when you need to know if two references are actually pointing to the exact same object.
Python is
Keyword Examples
Here’s a quick example demonstrating the use of the is
keyword:
>>> a = [1, 2, 3]
>>> b = a
>>> c = [1, 2, 3]
>>> a is b
True
>>> a is c
False
>>> a == c
True
In this example, a
and b
both refer to the same list object, so a is b
returns True
. However, a
and c
are two distinct objects with the same content, so a is c
returns False
. The expression a == c
returns True
because the lists have the same contents, even though they are different objects.
Python is
Keyword Use Cases
- Checking whether two variables refer to the same object
- Determining if a variable is
None
usingis None
Related Resources
Tutorial
Python '!=' Is Not 'is not': Comparing Objects in Python
In this quick and practical tutorial, you'll learn when to use the Python is, is not, == and != operators. You'll see what these comparison operators do under the hood, dive into some quirks of object identity and interning, and define a custom class.
For additional information on related topics, take a look at the following resources:
- Memory Management in Python (Tutorial)
- Variables in Python: Usage and Best Practices (Tutorial)
- Comparing Python Objects the Right Way: "is" vs "==" (Course)
- How Python Manages Memory (Course)
- Variables in Python (Course)
- Variables in Python: Usage and Best Practices (Quiz)