How To Fix Error “TypeError: list indices must be integers or slices, not str” in Python

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

If you are having trouble with the problem “TypeError: list indices must be integers or slices, not str”, let’s read this article. We will help you understand this error and give you some solutions to fix it. Now, let’s follow us.

The difference between using indices and using slices

Using indices is using an integer, and the program will return a list value. Using slices is to specify integers specifying the size of the start, end, and step. This method returns a sublist of the original list.

What is the “TypeError: list indices must be integers or slices, not str” Error?

TypeError is a standard Python exception. TypeError occurs when a programmer performs an operation on an unsupported or incorrect object or object type.

The error occurs when using a string for list indexing instead of indices or slices.

How to solve this error? 

Case 1: String Is Not Converted

We list four favorite dog breeds. The user can select one of the list indexes then the program will print the value of the selected list index.

Code:

favoriteDogBreed = ["French Bulldogs", "Poodles", "Beagles", "Rottweilers"]

choose = input("Choose a list index? ")
print(favoriteDogBreed[choose])

Output:

Choose a list index? 2
Traceback (most recent call last):
File "<string>", line 3, in <module>
    print(favoriteDogBreed[choose])
TypeError: list indices must be integers or slices, not str

We get the “TypeError: list indices must be integers or slices, not str” error. Since, in this example, the index list is in string form, we can fix this by adding the int():

Code:

favoriteDogBreed = ["French Bulldogs", "Poodles", "Beagles", "Rottweilers"]

choose = int(input("Choose a list index? "))
print(favoriteDogBreed[choose])

Output:

Choose a list index? 2
Beagles

Case 2: Treat Lists Like Dictionaries

In this example, each object (dog breed) will store more information about the average selling price. Then we write a piece of code to print out the average selling price of Poodles.

Code:

favoriteDogBreed = [
    {"Breed": "French Bulldogs", "Average selling price": 360},
    {"Breed": "Poodles", "Average selling price": 170},
    {"Breed": "Beagles", "Average selling price": 530},
    {"Breed": "Rottweilers", "Average selling price": 450}
]

if favoriteDogBreed["Breed"] == "Poodles":
    print(f'Average selling price: {favoriteDogBreed["Average selling price"]} dollars')

Output:

Traceback (most recent call last):
  File "<string>", line 8, in <module>
    if favoriteDogBreed["Breed"] == "Poodles":
TypeError: list indices must be integers or slices, not str

The “TypeError: list indices must be integers or slices, not str” error appears because we accessed the dictionary with the key “Breed” even though the dictionary was already in the list. To fix this, we have to get individual JSON objects by indexing the list with integers or indexing the list with slices. Finally, we will get the value from the dictionary.

Code:

favoriteDogBreed = [
    {"Name": "French Bulldogs", "Average selling price": 360},
    {"Name": "Poodles", "Average selling price": 170},
    {"Name": "Beagles", "Average selling price": 530},
    {"Name": "Rottweilers", "Average selling price": 450}
]

for i in range(len(favoriteDogBreed)):
    if favoriteDogBreed[i]["Name"] == "Poodles":
        print(
            f'Average selling price: {favoriteDogBreed[i]["Average selling price"]} dollars'
        )

Output:

Average selling price: 170 dollars

Case 3: Indexing Using A List Of Values

In the next case, we want to check if a particular value is in the list. We have dog breeds lined up on a list, and we want to check if Poodles are on this list or not.

Code:

dogBreedList = ["French Bulldogs", "Poodles", "Beagles", "Rottweilers"]

for dogBreed in dogBreedList:
    if dogBreedList[dogBreed] == "Poodles":
        print("Poodles are a breed of dog!")

Output:

Traceback (most recent call last):
  File "<string>", line 4, in <module>
    if dogBreedList[dogBreed] == "Poodles":
TypeError: list indices must be integers or slices, not str

This is quite simple since we already know the values, so there is no need to index the list.

Code:

dogBreedList = ["French Bulldogs", "Poodles", "Beagles", "Rottweilers"]

for dogBreed in dogBreedList:
    if dogBreed == "Poodles":
        print("Poodles are a breed of dog!")

Output:

Poodles are a breed of dog!

One way to check if an item is in a list is to use an if statement:

Code:

dogBreedList = ["French Bulldogs", "Poodles", "Beagles", "Rottweilers"]

if "Poodles" in dogBreedList:
    print("Poodles are a breed of dog!")

Output:

Poodles are a breed of dog!

Using .index() helps you get the index of an item:

Code:

dogBreedList = ["French Bulldogs", "Poodles", "Beagles", "Rottweilers"]
dog = dogBreedList.index("Poodles")
print(dogBreedList[dog])

Output:

Poodles

Summary

This article has shown the cause and how to fix the “TypeError: list indices must be integers or slices, not str” error in Python. I hope the information in this article was helpful to you.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *