Sitelet https://www.askpython.com/python/set/python-sets-resolving-typeerror

Python Sets: Fix the Indexing TypeError

Retrieving or testing a set member is the goal when Python reports TypeError: ‘set’ object is not subscriptable. A Python set stores distinct values and supports membership checks, but it does not support positional lookup.

I’ll explain what the error means and show how to choose an operation that matches the result you need.

TL;DR: Fix the Python Set Indexing Error

Use the expression that matches the result your code needs. For a presence check, write:

value in items

What Is a Python Set, and What Does Subscriptable Mean?

Curly braces with comma-separated values create a set. An empty pair of braces creates a dictionary, so use set() when an empty set is needed.

Square brackets request a position, as in sequence[0]. A set does not support that lookup, so items[0] raises TypeError: ‘set’ object is not subscriptable.

The traceback points to the expression that failed, not necessarily to the assignment that produced the set. Check the value at that line, then trace the right-hand side or function return that supplied it. A set conversion or a set comprehension may be upstream.

This short example distinguishes the common collection declarations:

colors = {"red", "blue"}
empty_set = set()
empty_dictionary = {}

A dictionary retrieves a value by a meaningful key, such as a record identifier.

How to Replace Set Indexing Step by Step

Find the failing expression and change the lookup at that line. Keep the surrounding logic intact unless it also assumes that the set has positions.

Step 1: Run the expression and compare its results

This script tries the invalid lookup, tests for a member, and prints a sorted list. Run the named file:

python3 set_indexing_demo.py
TypeError: 'set' object is not subscriptable
apple present: True
sorted values: ['apple', 'orange', 'pear']
first sorted value: apple
Terminal output showing a set indexing TypeError, membership result, and sorted values

The captured output shows the exception, a membership result, the sorted list, and its first element.

Step 2: Match the operation to the data

Each row includes an expression and the result it provides:

Required resultOperationWhat it provides
Check for one valuevalue in itemsA Boolean membership result
Apply work to every memberfor value in itemsOne visit to each member
Select the first comparable value in sorted ordersorted(items)[0]A position in a newly sorted list
Take any member when the choice does not matternext(iter(items), default)A member, or the supplied default for an empty set
Preserve a known position or repeated entryUse a list or tupleA sequence whose positions represent its elements

next(iter(items), default) avoids StopIteration when the set is empty. Choose a default that cannot be mistaken for a valid member, or check emptiness before using the returned value.

For a custom order, pass a key to sorted() that extracts a record field or normalizes text case. The Python list sorting guide explains how to choose that key.

list(items) creates a sequence from the members that remain in the set. It cannot restore the original order after conversion, so keep the source list when that order matters.

Edge Cases When Working with Sets

The table pairs common symptoms with practical corrections.

CaseSymptomFix
Unordered membersitems[0] raises TypeError because a set has no numeric positionUse membership or iteration, or apply sorted() when sorted order is intended
Unhashable memberAdding a list such as [1, 2] raises TypeErrorUse a tuple whose contents are hashable, or keep the record in a list
Repeated valuesAdding an existing value leaves one distinct memberKeep a list or count occurrences in a dictionary
Empty set{} creates a dictionaryCall set()
Possibly absent valueremove(value) raises KeyError when the value is absentUse discard(value) when absence should be ignored
Changing size during iterationSet changes while a loop is traversing itBuild a new set or loop over a copy
Incomparable sort valuessorted() cannot compare every pairNormalize values or pass an explicit key

The constructor splits a string into character candidates, then keeps its distinct values. Use [“banana”] as the input when the whole word should be one member.

Use len(items) for the current number of set members. An empty set has length zero.

Passing a dictionary to set() collects its keys. If the task needs unique values instead, use the dictionary’s values view as the input and confirm that those values are hashable.

Python compares strings case-sensitively, so Admin and admin are distinct members. Normalize input and later lookup values consistently if the application treats those labels as equivalent.

A dictionary view reflects later changes to its mapping, while a set created from that view is a separate result. Use the view for current data or rebuild the set when a fresh snapshot is needed. See the built-in types reference for dictionary views.

Converting mapping.values() to a set drops repeated values, so use the view directly when each occurrence matters.

Constructing a set from a generator consumes it, leaving no values for a later pass. Create a fresh generator or save the values before conversion when the program needs a second pass.

Union, intersection, difference, and symmetric difference answer different questions about two groups. The table gives the operator and the part of each input that survives.

OperationResultExample question
Union, |Members from either setWhich labels are assigned or required?
Intersection, &Members shared by both setsWhich permissions are common?
Difference, –Members in the left set but not the rightWhich required labels are missing?
Symmetric difference, ^Members in exactly one setWhich labels differ between configurations?
Subset, <=True when every left member belongs to rightAre all required labels allowed?
Disjoint, isdisjoint()True when sets share no memberDo these groups overlap?

These operators are useful for comparing permissions, configuration labels, or other groups of unique values.

For example, required – available finds missing labels, while available – required finds labels that were added beyond the requirement.

Treat a collection’s return type as part of a function’s interface. If branches return different types, normalize the result or document the difference and test each branch, including its empty case.

The integers 1 and the Boolean True compare equal and share a hash, so a set treats them as one member. Store a tagged value if the distinction between those types matters to the program.

A hashable value keeps its hash constant during its lifetime, and objects that compare equal must share that hash, as the Python glossary defines. Custom classes must follow this contract.

A frozenset is an immutable version of a set. Use it when the collection itself should not be updated after creation.

A set comprehension can also build a filtered result without a separate loop. For example, select the values that meet a condition while keeping the output as a set of distinct members.

For broader exception context, see Python exceptions and their handling. The Python set documentation covers supported set operations.

Conclusion: Match the Collection to the Lookup

Use the official set reference to check supported operations and their behavior. It also documents frozenset operations.

FAQ

These answers cover common questions about set lookup.

Are Python sets ordered?

A set does not provide positional indexing. Use a list when input order matters, or sorted() when sorted order is appropriate.

How do I get one item from a set?

Use next(iter(items), default) when any member is acceptable, or sort comparable members before choosing a sorted position.

How do I create an empty set in Python?

Call set(). Empty braces create a dictionary.

Shreya Bose
Shreya Bose
Articles: 104