0
0
Pythonprogramming~5 mins

Set creation in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Set creation
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the list gets bigger, the time to create the set grows roughly in direct proportion.

Input Size (n)Approx. Operations
10About 10 insertions
100About 100 insertions
1000About 1000 insertions

Pattern observation: Doubling the input roughly doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to create a set grows linearly with the number of items.

Common Mistake

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

Interview Connect

Understanding how set creation scales helps you explain efficiency clearly and shows you know how data structures behave with growing data.

Self-Check

"What if we created a set from a list that already has only unique items? How would the time complexity change?"