Home βΊ Problems βΊ TypeError: sets cannot be indexed
TypeError: sets cannot be indexed
π Fix the bug 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 a fix-the-bug problem: a short program is given in its broken state, and the task is to repair the code so it produces the required output. The interactive editor runs your fixed version in the browser and checks it for you β no setup, no local interpreter.
Difficulty: easy β the fix or the trick is normally a single line, and a careful read should be enough.
The challenge
This program crashes with TypeError because sets have no positions. Fix it (sort first) so it prints 3.
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 error it raises
Run the broken snippet and Python stops with this exact error: TypeError: 'set' object is not subscriptable. Match it to the Python errors guide, then repair the line that produced it β knowing the message is half the fix.
The snippet
The interactive editor pre-fills exactly this code, broken and ready to repair:
s = {6, 8, 3}
print(s[0])Understand the rule
A Python `set` is an unordered hash table built for O(1) membership checks (`x in s`) and deduplication β NOT positional storage. Because elements in a set have no index `0` or `-1`, writing `my_set[0]` immediately raises `TypeError: 'set' object is not subscriptable`.
How to trace it
- Evaluating `my_set[0]` invokes the subscript operator (`__getitem__`) on the `set` object.
- Unlike `list`, `tuple`, `str`, and `dict`, the `set` class does not implement `__getitem__`.
- Python raises `TypeError: 'set' object is not subscriptable`.
- Convert to a sorted list (`sorted(my_set)[0]`), iterate with `for x in my_set:`, or use `min(my_set)` / `next(iter(my_set))` depending on intent.
Common wrong fixes
- Converting with `list(my_set)[0]` when deterministic order matters β hash table iteration order on sets can vary across runs unless you use `sorted(my_set)` or `min(my_set)`!
- Accidentally creating a `set` with `{10, 20, 30}` curly braces when you meant a `list` `[10, 20, 30]`.
- Trying to slice a set (`my_set[:2]`), which fails with the exact same `not subscriptable` error.
Rule to remember
Sets have membership (`in`) and iteration (`for`), never positions β use `sorted(s)` or switch `{...}` to `[...]` when you need indexing.
More sets problems
Keep going
- Python debugging guide β a systematic method for finding bugs like this one fast.
- Browse every sets problem in this topic.
- Common Python errors and what they actually mean, plus the Python glossary for any term used on this page.