Skip to main content

Fixed: "TypeError: list indices must be integers or slices, not str" with a Hugging Face Pipeline's top_k

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

A loop over a Hugging Face text-classification pipeline's results failed with TypeError: list indices must be integers or slices, not str. The pipeline was created with top_k=None, and given one text, it returned a list inside a list, so the loop got a list where it expected a result. Passing top_k=None when calling the pipeline, instead of when creating it, returns the flat list the loop expects.

What I Was Doing​

I wanted the score of every emotion for one sentence, with bhadresh-savani/distilbert-base-uncased-emotion in Transformers 5.26.0 on Python 3.14. top_k=None asks for every label, and I set it when creating the pipeline:

nested.py
from transformers import pipeline

classifier = pipeline(
"text-classification",
model="bhadresh-savani/distilbert-base-uncased-emotion",
revision="98864ce5bb9cb58a41e882e62f1d8e55173b5ac6",
top_k=None,
)

for result in classifier("What a lovely day."):
print(result["label"], result["score"])
Terminal
uv run python nested.py

What I Expected​

Six lines, one per emotion, each with its label and score.

What I Got​

Output
Loading weights: 100%|██████████████████████████████████████████| 104/104 [00:00<00:00, 9106.63it/s]
Traceback (most recent call last):
File "/Users/you/source/top-k-demo/nested.py", line 11, in <module>
print(result["label"], result["score"])
~~~~~~^^^^^^^^^
TypeError: list indices must be integers or slices, not str

The terminal after uv run python nested.py: the weights loading, then a traceback pointing at result["label"] on line 11 of nested.py and ending in TypeError: list indices must be integers or slices, not str.

Python's message means result is a list, and a list can't be read with a text key like "label": only with a position number, such as result[0].

What I Checked​

What the pipeline returned. I printed the result instead of looping over it:

nested_print.py
from transformers import pipeline

classifier = pipeline(
"text-classification",
model="bhadresh-savani/distilbert-base-uncased-emotion",
revision="98864ce5bb9cb58a41e882e62f1d8e55173b5ac6",
top_k=None,
)

print(classifier("What a lovely day."))
Output
Loading weights: 100%|█████████████████████████████████████████| 104/104 [00:00<00:00, 13600.46it/s]
[[{'label': 'love', 'score': 0.9933533668518066}, {'label': 'joy', 'score': 0.003395110834389925}, {'label': 'surprise', 'score': 0.0013922249199822545}, {'label': 'sadness', 'score': 0.0007663396536372602}, {'label': 'fear', 'score': 0.0006297506624832749}, {'label': 'anger', 'score': 0.0004632087948266417}]]

Two opening brackets, [[: the six results are in a list, and that list is the only item of another list. The loop's first result was the inner list.

Why one text gets two lists. In transformers/pipelines/text_classification.py, the pipeline wraps the result of a single text in an extra list when top_k isn't among the arguments of the call:

transformers/pipelines/text_classification.py (excerpt, 5.26.0)
_legacy = "top_k" not in kwargs
if isinstance(inputs[0], str) and _legacy:
# This pipeline is odd, and return a list when single item is run
return [result]
else:
return result

kwargs holds the arguments of this call only. top_k=None given to pipeline(...) isn't among them, so the extra list is added around the six results.

Whether it's known. An issue on Transformers, huggingface/transformers#25251, "Defining top_k within pipeline changes output from list to nested list", reported it in 2023. A maintainer answered: "I agree that this is inconsistent but I don't think there is much to do about it now since this has been the case for the past three years, and making any change would break a lot of users code." The issue is closed, and the code above shows the behaviour is still there in 5.26.0.

Why It Happens​

The text-classification pipeline returns a different shape depending on where top_k is set. Given to the call, top_k makes the pipeline return a flat list of results. Given only to pipeline(...), the pipeline adds a list around the results of a single text, for compatibility with older code. A loop written for the flat list then gets the inner list, and indexing it with "label" fails.

The Fix​

Give top_k=None to the call instead of to pipeline(...):

nested.py
from transformers import pipeline

classifier = pipeline(
"text-classification",
model="bhadresh-savani/distilbert-base-uncased-emotion",
revision="98864ce5bb9cb58a41e882e62f1d8e55173b5ac6",
)

for result in classifier("What a lovely day.", top_k=None):
print(result["label"], result["score"])

The fixed nested.py in a macOS-style code window: the text-classification pipeline created without top_k, and the loop calling classifier on What a lovely day. with top_k=None and printing each result's label and score.

After the Fix​

Terminal
uv run python nested.py
Output
Loading weights: 100%|█████████████████████████████████████████| 104/104 [00:00<00:00, 15870.75it/s]
love 0.9933533668518066
joy 0.003395110834389925
surprise 0.0013922249199822545
sadness 0.0007663396536372602
fear 0.0006297506624832749
anger 0.0004632087948266417

The terminal after the fix: the weights loading, then six lines from love with 0.9934 down to anger with 0.00046.

Six emotions, sorted from the highest score down, with the same scores as the nested list above. The commands work unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Setting top_k in pipeline(...) and calling it with one textOne extra list around the resultsSet top_k in the call
Fixing the loop with result[0]["label"]The loop runs once, over the one inner list, and prints only its first labelFix the shape at the call, so each result is one label

Troubleshooting​

SymptomLikely causeFix
A list of texts gives a list of listsThat's expected: one list of results per textLoop over the texts' lists, then over each list's results
The scores are all there but not in label ordertop_k=None sorts results by scoreLook labels up by result["label"]

FAQ​

Can I keep top_k=None in pipeline(...)?​

Yes, if your code expects the extra list. With top_k=None in pipeline(...), one text returned a list of length 1, and two texts returned two lists of six results each. Read the first item for a single text: classifier("What a lovely day.")[0].

Does this happen with other pipelines?​

The code above is in the text-classification pipeline. Other pipelines have their own output shapes: print a result once before writing a loop over it.

Conclusion​

TypeError: list indices must be integers or slices, not str came from a loop over [[...]]: the text-classification pipeline adds a list around a single text's results when top_k is set in pipeline(...) rather than in the call. Calling classifier("What a lovely day.", top_k=None) returned the six results as a flat list, and the loop printed them.

Additional Resources​