
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What Does is Operator Do in Python
The "is" operator in Python is an identity operator. This operator checks whether two variables refer to the same object in memory. It returns boolean values as a result.
Each object in the computer's memory is assigned a unique identification number (id) by the Python interpreter. Identity operators check if the id() of two objects is the same. The 'is' operator returns false if id() values are different and true if they are the same.
Syntax of Python (is) Operator
The "is" operator follows the following syntax in Python:
variable1 is variable2
The "is" operator needs two variables to check whether the variable belongs to the same object or not. In the above syntax, the "is" operator will return true if both variables belong to the same object and false if not.
Examples of (is) Operator
In this section, we will see some examples of using the "is" operator in Python.
Example 1
The following is a simple example of using the "is" operator in Python. In the example below, a and b point to the same list in memory, so the expression a is b is true. But c is a separate list with the same values, so the expression a is c is false because they are different objects in memory.
a= [1,2,3] b=a c= [1,2,3] print(f"The result of a is b is",a is b) print(f"The result of a is c is",a is c)
Following is the output of the above program -
The result of a is b is True The result of a is c is False
Example 2
In the following example, we have used the "is" operator on the string.
a= "Tutorialspoint" b=a c= "Tutorialspoint" print(f"The result of a is b is",a is b) print(f"The result of a is c is",a is c)
Following is the output of the above program -
The result of a is b is True The result of a is c is True
In this example, the expression a is b returns True because a is assigned to b, meaning they refer to the same memory. Similarly, a is c also returns True, even though a and c are separate variables, because strings are immutable, and Python reuses the same object for the same value to save memory.
Conclusion
In this article, we explored how the "is" operator works in Python. It is mainly used in situations where you need to check if two variables refer to the same object. As demonstrated, the "is" operator behaves differently for various data types like strings and lists, which is important to understand when using it.