← Back

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

  1. Evaluating `my_set[0]` invokes the subscript operator (`__getitem__`) on the `set` object.
  2. Unlike `list`, `tuple`, `str`, and `dict`, the `set` class does not implement `__getitem__`.
  3. Python raises `TypeError: 'set' object is not subscriptable`.
  4. 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

Rule to remember

Sets have membership (`in`) and iteration (`for`), never positions β€” use `sorted(s)` or switch `{...}` to `[...]` when you need indexing.

Solve it in the interactive editor β†’

More sets problems

Keep going