← Back

Home β€Ί Problems β€Ί Set removes duplicates automatically

Set removes duplicates automatically

🧠 Predict the output Topic: sets Difficulty: easy Free

What this problem practises

Sets are unordered containers that drop duplicates on insertion. Membership tests are fast, insertion order is not preserved, and {} builds an empty dict β€” not an empty set.

This is an output-prediction problem: read the snippet carefully and write down exactly what it prints before anything runs. These questions are interview staples because they test whether you know the language rules, or merely recognise their syntax.

Difficulty: easy β€” the fix or the trick is normally a single line, and a careful read should be enough.

The challenge

The code runs in PyDebug’s in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.

The snippet

The interactive editor pre-fills exactly this code β€” read it, then submit your prediction:

numbers = [1, 2, 2, 3, 3, 3]
unique = set(numbers)
print(len(unique))
print(3 in unique)

Understand the rule

Building a set discards duplicates on insertion: set([1, 2, 2, 3]) holds three elements, and len() reflects the deduplicated count. The second rule these puzzles test: sets are unordered, so printed element order is not guaranteed to match insertion order β€” a correct prediction states the members and the length, not a specific sequence.

How to trace it

  1. List the input values and strike out every repeat β€” first occurrence stays, later ones vanish silently.
  2. Count the survivors for any len() call.
  3. Watch equality subtleties: 1, 1.0 and True collapse to one element because they compare equal.
  4. For membership tests (x in s), answer from the deduplicated set.

Common wrong fixes

Rule to remember

Sets keep one copy of each equal value and promise no order. Predict membership and count β€” and remember set() (not {}) is the empty set.

Solve it in the interactive editor β†’

πŸ’Ό Learning path: Interview Practice

Problem 13 of 16 in this path. Work them in order β€” each one builds on the rule before it.

← Tuple immutabilityNext in path: Default parameter values β†’

More sets problems

Keep going