Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 24375

Python Morsels: Equality versus identity in Python

$
0
0

Equality checks whether two objects represent the same value. Identity checks whether two variables point to the same object.

The equality operator in Python

Let's say we have two variables that point to two lists:

>>> a=[2,1,3]>>> b=[2,1,3,4]

When we use the == operator to check whether these lists are equal, we'll see that they are not equal:

>>> a==bFalse

These lists don't have the same values right now, so they're not equal.

Let's update the first list so that these two lists do have equivalent values:

>>> a.append(4)>>> a[2, 1, 3, 4]

If we use == again, we'll see that these lists are equal now:

>>> a==bTrue

Python's == operator checks for equality. Two objects are equal if they represent the same data.

The is operator in Python

Python also has an is …

Read the full article: https://www.pythonmorsels.com/equality-vs-identity/


Viewing all articles
Browse latest Browse all 24375

Trending Articles