DEV Community

Carmine Scarpitta
Carmine Scarpitta

Posted on

3 3

'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 ==

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay