Services
Back

Question:

What is the difference between the "is" operator and the "==" operator?

How often asked: Constantly

Suggested by: ALittleMoron


Answer:

The difference is that == compares by value, while is compares by memory address.

Two objects can be equal in value or structure, but they may not be the same object. For example, ["a", "b"] == ["a", "b"] will return True, but ["a", "b"] is ["a", "b"] will return False.


Interview answer explanation:

This question is an introduction to understanding how Python stores objects internally.

Understanding what a memory address is and why seemingly identical objects can have different memory addresses (that is, essentially be different objects) is an important part of the language. It's also closely related to pointers, which are hidden in Python, but can play a significant role in coding in other languages ​​like C, C++, and Rust. Understanding all these topics is important for understanding concepts common to all languages.

The interviewer can further delve into this question, clarifying why exactly is and == are different, and also why lists work the same way, while, for example, the 5 is 5 returns to True.


External resources: