l1=[1,2,3]
l2=[1,2,3]
print(l1 is l2)
# False
Can anyone explain this piece of code. Why is it false ?
l1=[1,2,3]
l2=[1,2,3]
print(l1 is l2)
# False
Can anyone explain this piece of code. Why is it false ?
is
operator checks if both the operands refer to the same object or not. In this l1 and l2 are two different objects, so, it returns False.
Please note that two list instances don't refer to the same object just because they have the same contents.
You can use id
to check if both are reference to same object. Check the below code. In this case, you can see that l1
and l2
are different objects, whereas l2
and l3
refer to the same object. Please note that use of ==
operator in the below code and how it returns True
if the contents of the list are same.
l1=[1,2,3]
l2=[1,2,3]
l3 = l2
print("l1 = %s" %(id(l1)))
print("l2 = %s" %(id(l2)))
print("l3 = %s" %(id(l3)))
print(l1 is l2)
print(l2 is l3)
print(l1 == l2)
print(l2 == l3)
Output:
l1 = 139839807952728
l2 = 139839807953808
l3 = 139839807953808
False
True
True
True
Note: If you want to compare two objects based on their content, use the ==
operator
is
: tests if two variables point the same object, not if two variables have the same value.
# - Darling, I want some pudding!
# - There is some in the fridge.
pudding_to_eat = fridge_pudding
pudding_to_eat is fridge_pudding
# => True
# - Honey, what's with all the dirty dishes?
# - I wanted to eat pudding so I made some. Sorry about the mess, Darling.
# - But there was already some in the fridge.
pudding_to_eat = make_pudding(ingredients)
pudding_to_eat is fridge_pudding
# => False
So where ==
operator compares the values of two objects or variables, is
operator checks if the objects compared are same or not. You can think of it like comparing pointers
.