Python is keyword is an identity operator that checks whether two objects refer to the same memory location.
It evaluates to True if the operands point to the same object, and False otherwise.
The syntax for using the is keyword is straightforward.
It follows the general form: object1 is object2.
Here, object1 and object2 are the variables or expressions being compared.
Let’s take a look at some examples to illustrate its usage:
Example 1: Comparing lists
x = [1, 2, 3] y = [1, 2, 3] z = x print(x is y) # False print(x is z) # True
In this example, x and y are two distinct lists that have the same values.
The is keyword returns False since x and y are stored at different memory locations.
However, x and z refer to the same object, resulting in True when comparing them using is.
Example 2: Comparing integers
a = 10 b = a print(a is b) # True
Here, a and b both refer to the same integer object, 10.
Therefore, the is keyword returns True.
Example 2: Comparing with None
value = None if value is None: print("The variable is None.")
The is keyword is commonly used to check if a variable is None.
In Python, None is a special object used to denote the absence of a value.
Since None is a singleton object, using is to compare a variable with None is recommended over the ‘==’ operator.
Key Points to Remember
- The is keyword is used to compare object identity, not object values.
- It evaluates to True if the operands point to the same memory location, and False otherwise.
- Use the is keyword when you need to check if two variables refer to the same object.
- If you want to compare object values, use the equality operator ‘==’ instead of is.
Conclusion
The is keyword in Python offers a concise and efficient way to compare object identity.
By understanding its purpose and proper usage, you can harness its power to write clean and reliable code.