0
0
Pythonprogramming~5 mins

Identity operators (is, is not) in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Identity operators (is, is not)
O(1)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

Look for loops or repeated checks.

  • Primary operation: Single identity check using is
  • How many times: Exactly once, no loops or recursion
How Execution Grows With Input

Checking if two variables are the same object takes the same time no matter how big the objects are.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The operation count stays the same even if the data grows.

Final Time Complexity

Time Complexity: O(1)

This means the check takes the same short time no matter how big the data is.

Common Mistake

[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.

Interview Connect

Understanding identity checks helps you write clear and efficient code, and shows you know how Python handles objects behind the scenes.

Self-Check

What if we changed is to ==? How would the time complexity change?