Identity operators (is, is not) in Python - Time & Space Complexity
When we use identity operators like is and is not, we check if two things are the exact same object.
We want to see how long it takes to do this check as the data size changes.
Analyze the time complexity of the following code snippet.
my_list = [1, 2, 3, 4, 5]
other_list = my_list
if my_list is other_list:
print("They are the same object")
else:
print("They are different objects")
This code checks if two variables point to the exact same list object.
Look for loops or repeated checks.
- Primary operation: Single identity check using
is - How many times: Exactly once, no loops or recursion
Checking if two variables are the same object takes the same time no matter how big the objects are.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The operation count stays the same even if the data grows.
Time Complexity: O(1)
This means the check takes the same short time no matter how big the data is.
[X] Wrong: "Checking if two lists are the same with is takes longer if the lists are bigger."
[OK] Correct: The is operator only checks if both variables point to the same object, not their contents, so size does not affect the time.
Understanding identity checks helps you write clear and efficient code, and shows you know how Python handles objects behind the scenes.
What if we changed is to ==? How would the time complexity change?