Python TypeError ‘set’ object is not subscriptable

Minimal Error Example

Given the following minimal example where you create a set and attempt to access an element of this set using indexing or slicing:

my_set = {1, 2, 3}
my_set[0]

If you run this code snippet, Python raises the TypeError: 'set' object is not subscriptable:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 2, in <module>
    my_set[0]
TypeError: 'set' object is not subscriptable

Why Does the Error Occur?

The Python TypeError: 'set' object is not subscriptable occurs if you try to access an element of a set using indexing or slicing that imply an ordering of the set.

However, sets are unordered collections of unique elements: they have no ordering of elements. Thus, you cannot use slicing or indexing, operations that are only possible on an ordered type.

🌍 Recommended Tutorial: The Ultimate Guide to Python Sets

How to Fix the Error?

How to fix the TypeError: 'set' object is not subscriptable?

To fix the TypeError: 'set' object is not subscriptable, either convert the unordered set to an ordered list or tuple before accessing it or get rid of the indexing or slicing call altogether.

Here’s an example where you convert the unordered set to an ordered list first. Only then you use indexing or slicing so the error doesn’t occur anymore:

my_set = {1, 2, 3}

# Convert set to list:
my_list = list(my_set)

# Indexing:
print(my_list[0])
# 1

# Slicing:
print(my_list[:-1])
# [1, 2]

Alternatively, you can also convert the set to a tuple to avoid the TypeError: 'set' object is not subscriptable:

my_tuple = tuple(my_set)

Let’s end this article with a bit of humor, shall we? πŸ™‚

Programmer Humor

There are only 10 kinds of people in this world: those who know binary and those who don’t.
πŸ‘©πŸ§”β€β™‚οΈ
~~~

There are 10 types of people in the world. Those who understand trinary, those who don’t, and those who mistake it for binary.

πŸ‘©πŸ§”β€β™‚οΈπŸ‘±β€β™€οΈ