Python Mastery – From Basics to Brilliance / Python Fundamentals

Object Identity - is vs ==

πŸ†” Object Identity β€” is vs ==

Python provides two different operators for comparing objects:

  • == β†’ Checks whether values are equal

  • is β†’ Checks whether two variables refer to the same object


βš–οΈ == β€” Value Comparison

The == operator checks whether two objects have the same value.

x = [1, 2, 3]
y = [1, 2, 3]

print(x == y) #True

Even though x and y are separate lists, their contents are the same.

πŸ†” is β€” Identity Comparison

The is operator checks whether two variables refer to the exact same object in memory.

x = [1, 2, 3]
y = [1, 2, 3]

print(x is y) #False

x and y contain the same values, but they are two different list objects.


πŸ”— Same Object Example

x = [1, 2, 3]
y = x

print(x == y)   # True
print(x is y)   # True

Here, y = x makes both variables refer to the same object.


⭐ Important Example with None

is is commonly used when checking for None:

name = None

if name is None:
    print("No name provided")

Prefer:

name is None

over:

name == None

πŸ”‘ is vs ==

==

is

Compares values

Compares identity

Asks: "Are they equal?"

Asks: "Are they the same object?"

Uses equality comparison

Checks object identity

Example: x == y

Example: x is y

🧠 Easy Way to Remember

==  β†’ Same VALUE? πŸ’°
is  β†’ Same OBJECT? πŸ†”