DEV Community

Carmine Scarpitta
Carmine Scarpitta

Posted on

'is' vs '==' to Check if Two Elements are Equal in Python

Python objects can be compared using two operators: == and is.

Examples

Compare x to None using is:

if x is None:
    print('Object x is None')
Enter fullscreen mode Exit fullscreen mode

Compare x to the empty string '' using ==:

if x == '':
    print('x is an empty string')
Enter fullscreen mode Exit fullscreen mode

Apparently the two operators is and == can be used interchangeably, but this is not the case.

Difference between == and is

== is a equality operator. It is used to check if two objects are equal or not.

is is an identity operator. It is used to check if two objects are actually the same object or not. In other words, it checks if the two objects share the same memory location.

When should we use 'is' and when '=='?

In general, if you are comparing an object to a sigleton like None, True or False you should always use is. There are some exceptions, but most of the time this is the case.

For all the other object types (e.g. strings and numbers), using is can lead to unexpected behavior. To compare these object types, you must always use ==.

Conclusions

Data Type Compare using
None is
bool is
str ==
int ==
float ==
list ==
tuple ==
dict ==
bytes ==
dict ==

Top comments (0)