Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 12, 2022 10:50 pm GMT

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

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

if x == '':    print('x is an empty string')

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 TypeCompare using
Noneis
boolis
str==
int==
float==
list==
tuple==
dict==
bytes==
dict==

Original Link: https://dev.to/cscarpitta/is-vs-to-check-if-two-elements-are-equal-in-python-5d08

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To