Set creation in Python - Time & Space Complexity
When we create a set from a list, we want to know how the time it takes changes as the list gets bigger.
We ask: How does the work grow when the input size grows?
Analyze the time complexity of the following code snippet.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
unique_numbers = set(numbers)
This code takes a list of numbers and creates a set to keep only unique values.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each item from the list into the set.
- How many times: Once for each item in the list.
As the list gets bigger, the time to create the set grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 insertions |
| 100 | About 100 insertions |
| 1000 | About 1000 insertions |
Pattern observation: Doubling the input roughly doubles the work.
Time Complexity: O(n)
This means the time to create a set grows linearly with the number of items.
[X] Wrong: "Creating a set takes the same time no matter how many items there are."
[OK] Correct: Each item must be checked and added, so more items mean more work.
Understanding how set creation scales helps you explain efficiency clearly and shows you know how data structures behave with growing data.
"What if we created a set from a list that already has only unique items? How would the time complexity change?"