Python - Difference Between ‘is’ and ‘==’
python-mini (1 Part Series)
In python the is
operator compares if two variables point to the same object.
The ==
operator checks the “values” of the variables are equal.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
a = [1, 2, 3]
b = [1, 2, 3]
c = a
if (a == b):
print("True")
else:
print("False")
if (a is b):
print("True")
else:
print("False")
if (a == c):
print("True")
else:
print("False")
if (a is c):
print("True")
else:
print("False")
Or with more “pythonic” and clearer syntax:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b)
print(a is b)
print(a == c)
print(a is c)
The output will be:
True
False
True
True
For detail, you can check memory adresses of these objects to see whether they are same or not:
print(hex(id(a)))
print(hex(id(b)))
print(hex(id(c)))
Output:
0x7ff7b59d8488
0x7ff7b59d84c8
0x7ff7b59d8488
All done!
Subscribe
Read Related