How to Fix TypeError: List Indices Must Be Integers, Not STR in Python

Preet Sanghavi Feb 02, 2024
  1. Understand the Root Cause of the TypeError: list indices must be integers or slices, not str in Python
  2. Replicate the TypeError: list indices must be integers or slices, not str in Python
  3. Solve the Error in Python
How to Fix TypeError: List Indices Must Be Integers, Not STR in Python

In this tutorial, we aim to explore how to get rid of the TypeError: list indices must be integers or slices, not str.

This article tackles the following topics.

  1. Understanding the root cause of the problem.
  2. Replicating the issue.
  3. Resolving the issue.

Understand the Root Cause of the TypeError: list indices must be integers or slices, not str in Python

TypeError mainly occurs in Python whenever there is a problem with the type of data being operated. For example, adding two strings would result in a TypeError because you cannot add two strings.

Replicate the TypeError: list indices must be integers or slices, not str in Python

This problem can be replicated with the help of the following block of code.

Let’s assume we’re trying to assign the score as 1, age as 2 and rating as 3 for a particular player. We’re then trying to access the score of the same player.

player = [1, 2, 3]
print(player["score"])

As we can see from the code block above, we are trying to find an attribute score from an array named player.

The output of the code block is below.

TypeError: list indices must be integers or slices, not str

Solve the Error in Python

To resolve this problem, we can directly use a dictionary in Python. The previously illustrated code can be changed to the following to eliminate the error.

player = {"score": 1, "age": 2, "rating": 3}
print(player["score"])

The output of the code block is below.

1

Thus, with the help of this tutorial, we can solve this TypeError in Python.

Preet Sanghavi avatar Preet Sanghavi avatar

Preet writes his thoughts about programming in a simplified manner to help others learn better. With thorough research, his articles offer descriptive and easy to understand solutions.

LinkedIn GitHub

Related Article - Python Error