Python is operator

In Python, is Operator is used to check if two variables have the same object.

Python is Operator is an identity operator, because, it compares objects if they are same or not.

The id property of the object is used for this comparison.

Syntax

The syntax to check if a and b have the same object is

</>
Copy
a is b

The above expression returns True if both a and b are the same object, else it returns False.

Examples

1. When a and b are integers

In the following program, we take two numbers: a, b; assign them with same integer value, and check if both the variables hold the same object.

main.py

</>
Copy
a = 5
b = 5

if (a is b):
  print("a and b hold the same object.")
else :
  print("a and b do not hold the same object.")

Output

a and b hold the same object.

For integers, the id of the object is same as the integer value. Therefore, these two objects are same.

2. When a and b are lists

In the following program, we take two lists in a, b with same elements.

main.py

</>
Copy
a = [5, 10, 15]
b = [5, 10, 15]

if (a is b):
  print("a and b hold the same object.")
else :
  print("a and b do not hold the same object.")

Output

a and b do not hold the same object.

Even though the two lists have same elements in the same order, their id values are different, and hence a is not b.

Now, let us create a variable c from a, and check if a and c hold the same object.

main.py

</>
Copy
a = [5, 10, 15]
c = a

if (a is c):
  print("a and c hold the same object.")
else :
  print("a and c do not hold the same object.")

Output

a and c hold the same object.

While assigning the value in a variable to another variable, the same object is assigned to the new variable. Thus the two variables hold the same object.

You can check the working of this is operator with other data types, or user defined types.

For the above two programs, you may print the id property of the objects, and then you get a clear idea of the comparison used in is operator.

main.py

</>
Copy
a = [5, 10, 15]
b = [5, 10, 15]
c = a

print('id of a:', id(a))
print('id of b:', id(b))
print('id of c:', id(c))

Output

id of a: 140453705373056
id of b: 140453704467584
id of c: 140453705373056

The id of a and c are same, but that of a and b are different.

Conclusion

In this Python Tutorial, we learned about is Operator, its syntax, and usage, with examples.