In Python, the is
operator is used to check if two variables reference the same object in memory. It is often used to compare object identity rather than object equality. Here is the basic syntax of the is
operator:
object1 is object2
object1
andobject2
are the two objects you want to compare.
The result of the is
operator is a boolean value, either True
or False
, indicating whether object1
and object2
reference the same memory location or not.
x = [1, 2, 3]
y = x
result = x is y # This will be True because x and y reference the same list object.
print(result)
In this example, x
and y
reference the same list object in memory, so x is y
evaluates to True
.
Python is operator example
Here’s an example that demonstrates the use of the is
operator in Python:
# Creating two lists with the same content
list1 = [1, 2, 3]
list2 = [1, 2, 3]
# Checking if list1 and list2 reference the same object in memory
result = list1 is list2
# Printing the result
print(result)
Output:
In this example, we have two lists, list1
and list2
, which have the same content [1, 2, 3]
. However, they are two distinct list objects created in memory. When we use the is
operator to compare them, the result will be False
because list1
and list2
reference different objects in memory, even though their contents are the same.
If you want to compare the contents of these lists for equality, you should use the ==
operator, like this:
# Checking if the contents of list1 and list2 are equal
result = list1 == list2
print(result)
Using ==
, the result will be True
because it checks whether the elements in the lists are the same, regardless of whether they reference the same object in memory.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.