DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

Python - Difference Between 'is' and '=='

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")
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

The output will be:

True
False
True
True
Enter fullscreen mode Exit fullscreen mode

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)))
Enter fullscreen mode Exit fullscreen mode

Output:

0x7ff7b59d8488
0x7ff7b59d84c8
0x7ff7b59d8488
Enter fullscreen mode Exit fullscreen mode

All done!

Top comments (0)