Python is Keyword

python is operator 100% 22200

The is keyword in Python is used when we need to check whether two objects are same or not. For example:

a = {"Day": "Thu", "Month": "Dec"}
x = a
print(a is x)

a = [10, 20, 30]
x = a
print(a is x)

The output is:

True
True

Note - The is is used to check whether two variables in Python, refer to the same object or not. It returns True, if two variables refers to the same object. Otherwise returns False.

The is works similar to the == operator. The only difference is, == deals with values, whereas is deals with object.

Important - The is returns True, if specified objects are identical. Otherwise returns False

Since string and tuple are immutable, means value can not be changed when it is defined. Therefore any two equal strings are identical, because they refer to the same memory location. Similarly any two equal tuples are identical. For example, let's consider the following program:

x = ""
y = ""
print(x is y)

x = ()
y = ()
print(x is y)

x = tuple()
y = tuple()
print(x is y)

The output is:

True
True
True

And because list and dictionary objects are mutable, therefore:

x = []
y = []
print(x is y)

x = list()
y = list()
print(x is y)

x = dict()
y = dict()
print(x is y)

The output is:

False
False
False

The program given below is the last example program, demonstrating the is keyword in Python:

a = "codescracker"
b = "codescracker"
c = "Python Programming"
print(a is b)
print(a is c)

a = (10, 20, 80)
b = (10, 20, 80)
c = (20, 30, 40)
print(a is b)
print(a is c)

a = [1, 6, 9]
b = [1, 6, 9]
print(a is b)

a = {"Day": "Thu", "Month": "Dec"}
b = {"Day": "Thu", "Month": "Dec"}
print(a is b)

The output is:

True
False
True
False
False
False

Python Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!