Separate whether two references name the same object, whether values compare equal and whether state can change.
How It Works
The is operator compares identity, while == normally calls equality behavior. Two separate objects can compare equal. A mutable object can change after creation; equal contents today do not imply shared identity or permanent equality.
Object identity is relevant to aliasing and mutation; value equality is usually what business rules require.
Step-by-Step Example
first = [1, 2]
second = [1, 2]
alias = first
print(first == second)
print(first is second)
print(alias is first)
alias.append(3)
print(first, second)
Understanding the Example
- The expression '[1, 2]' supplies the value stored as 'first'. This value is then used or checked by the later statements.
- The expression '[1, 2]' supplies the value stored as 'second'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
True
False
True
[1, 2, 3] [1, 2]
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Make a shallow copy of a nested list and inspect which inner objects share identity.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Using is instead of == when comparing ordinary list or string values.
- Assuming two equal objects are also aliases of the same mutable storage.
Key Takeaways
- Separate whether two references name the same object, whether values compare equal and whether state can change.
- The is operator compares identity, while == normally calls equality behavior.
- Object identity is relevant to aliasing and mutation; value equality is usually what business rules require.