Python is keyword

The is keyword in Python is used to compare the identity of two objects. It checks whether two variables point to the same object in memory, not just whether their values are equal.

Example 

x = [1, 2, 3]

y = x

if x is y:

    print("x and y refer to the same object!")

Output:

x and y refer to the same object!

Syntax

variable1 is variable2
  • is: Checks if both variables refer to the same object.
  • is not: Checks if both variables refer to different objects.

Why Use is?

  1. Identity Check: Use is to determine whether two variables refer to the same object in memory.
  2. Comparison Beyond Value: Unlike ==, which checks equality of values, is checks object identity.
  3. Use with Singleton Objects: Commonly used with None, True, and False to check if a variable is a specific singleton.

Common Examples

1. Comparing Object Identity

a = [1, 2, 3]

b = [1, 2, 3]

print(a == b)  # True (values are equal)

print(a is b)  # False (different objects in memory)

Output:

True

False

2. Using is with Singleton None

value = None

if value is None:

    print("The value is None")

Output:

The value is None

3. Comparing Immutable Objects

x = 10

y = 10

if x is y:

    print("x and y are the same object")

Output:

x and y are the same object

Note: For small integers and strings, Python optimizes memory by reusing immutable objects, so is may return True.


4. Using is not

status = None

if status is not None:

    print("Status is set!")

else:

    print("Status is None")

Output:

Status is None

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top