Tuple vs list comparison in Python - Performance Comparison
When we compare two collections like tuples and lists, it is important to understand how long the comparison takes as the size grows.
We want to know how the time to compare changes when the collections get bigger.
Analyze the time complexity of the following code snippet.
list1 = [1, 2, 3, 4, 5]
tuple1 = (1, 2, 3, 4, 5)
if list1 == tuple1:
print("Equal")
else:
print("Not equal")
This code compares a list and a tuple element by element to check if they are equal.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Element-by-element comparison of the two sequences.
- How many times: Up to the length of the shorter sequence, comparing each pair once.
As the size of the list and tuple grows, the number of comparisons grows roughly the same.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 comparisons |
| 100 | 100 comparisons |
| 1000 | 1000 comparisons |
Pattern observation: The number of operations grows directly with the size of the sequences.
Time Complexity: O(n)
This means the time to compare grows linearly with the number of elements.
[X] Wrong: "Comparing a tuple is always faster than a list because tuples are immutable."
[OK] Correct: The comparison checks each element regardless of type; immutability does not speed up element-wise comparison.
Understanding how comparisons scale helps you write efficient code and explain your reasoning clearly during interviews.
"What if we compare two lists where one is a prefix of the other? How would the time complexity change?"