An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
'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 Type | Compare using |
---|---|
None | is |
bool | is |
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To