How the Python Operator ''=='' Works

DZone 's Guide to

How the Python Operator ''=='' Works

Add another tool to your belt with this quick and easy Python tutorial.

· Web Dev Zone ·
Free Resource


Slithery bio

This small article explains the exact difference between == and operators in Python with simple and easy to understand examples.

The == operator checks for equality whereas "is" operator checks if both the left and right operands are referring to the same object.

Let's understand this with an example

list1 = [1, 2, 3]
list2 = [1, 2, 3]

list1 == list2 # returns True

Because both lists list1 and list 2 have the same elements.

list1 is list2 # returns False

Because both the operands are referring to different objects. Let's confirm this by displaying the ids of both list1 and list2.


Now, I am defining a new list list3 from list2

list3 = list2

list1 is list3 # returns False
list2 is list3 # returns True

Both list2 and list3 are referring to a different object this time.


For smaller strings or integers you will see is operator returning True, but that is not the case with the larger strings or integers. This is because of how the interpreter maps string values to string objects[1]. Read String Interning Wikipedia article[2] to understand how this mapping happens.

# For smaller strings
str1 = 'abc'
str2 = 'abc'
str1 is str2 # returns True

# For larger strings
str1 = 'abc'*1000000
str2 = 'abc'*1000000
str1 is str2 # returns False

What’s Coming Next?

  • Python Dictionaries
  • Using UUID vs auto integer for Primary Key.


[1] - https://stackoverflow.com/a/25758019

[2] - https://en.wikipedia.org/wiki/String_interning

operator, operators, programming, python, python 101, tutorial, web dev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}