How to solve TypeError: ‘set’ object is not subscriptable

This is the article where I’ll show you how to solve TypeError: ‘set’ object is not subscriptable in Python.

I encountered a type error in Python, which I dealt with. So I want to show you how to do it when you also get a type error of ‘set’ object is not subscriptable.

What is type error “object is not subscriptable”

I have a defined set.

my_set = {'New York', 'Austin', 'Chicago'}

I’m sure that my set contains the value I need.

See also  How to Plot Errorbar Charts in Python with Matplotlib

The output of the below line is True.

print('New York' in my_set)

I wanted to access the value by index.

print(my_set[0])

I’m not able to access it by index because it throws me an error “object is not subscriptable”.

Traceback (most recent call last):
  File "C:\Users\Pythoneo\PycharmProjects\new.py", line 5, in 
    print(my_set[0])
TypeError: 'set' object is not subscriptable

Process finished with exit code 1

The error occurs because, by definition, the set data type contains data that is not sorted. For this reason, indexing (as well as slicing) does not work for the set data type.

How to solve TypeError: ‘set’ object is not subscriptable in Python

If you can’t access a value from a set data type, then use a different data type. In my case I changed set to list. In fact, the change in the code is changing the curly brackets to square brackets.

If you don’t want to use a list, you can change the data type to tuple or dictionary.