EasyConcept

What is the difference between is and == in Python?

Technology:
Python
Experience:
Intern,
Junior

Quick answer

== checks whether two objects have equal values, while is checks whether they are the exact same object in memory.

Detailed explanation

== calls the object's __eq__ method. is compares identity (the same as comparing id(a) == id(b)). Two separate lists with the same content are == but not is.

Use is for singletons, mainly None (if x is None), True and False. Do not use is to compare numbers or strings: CPython caches small integers and some strings, so the result can look right in a quick test and fail in real code.

Example

python
a = [1, 2]
b = [1, 2]
a == b        # True  (same value)
a is b        # False (different objects)
c = a
c is a        # True

if result is None:
    ...
  • PythonEasy

    What is the difference between a list and a tuple in Python?

    A list is mutable and can be changed after creation, while a tuple is immutable; tuples are slightly faster, use less memory and can be used as dictionary keys when their items are hashable.

    Intern 路 Junior 路 Data Structures
  • PythonEasy

    What are *args and **kwargs in Python?

    *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary, which lets a function accept a variable number of arguments.

    Junior 路 Mid-level 路 Functions & Scope
  • PythonMedium

    Why should you not use a mutable default argument in Python?

    Default argument values are evaluated once when the function is defined, so a default list or dictionary is shared between every call that does not pass its own, causing data to leak between calls.

    Junior 路 Mid-level 路 Functions & Scope
  • PythonMedium

    What is the difference between @staticmethod and @classmethod in Python?

    A classmethod receives the class as its first argument (cls) and can create or configure instances, while a staticmethod receives no automatic argument and is just a function placed inside the class namespace.

    Junior 路 Mid-level 路 Object-Oriented Programming
  • PythonMedium

    What are decorators in Python and how do they work?

    A decorator is a function that takes another function and returns a modified version of it, letting you add behaviour such as logging, caching or access control without changing the original code.

    Mid-level 路 Senior 路 Functions & Scope