[Solved] TypeError: List Indices Must Be Integers Or Slices, Not ‘Str’?

TypeError: List Indices Must Be Integers Or Slices, Not 'Str'

â—ˆ Overview

Aim: How to fix – TypeError: list indices must be integers or slices, not str in Python?

Example: Take a look at the following code which generates the error mentioned above.

Output:

Traceback (most recent call last):
File “D:/PycharmProjects/pythonProject1/error.py”, line 3, in
print(‘Second Subject: ‘, list1[index])
TypeError: list indices must be integers or slices, not str

Reason:

We encountered the TypeError because we tried to access the index of the list using a string which is not possible!

Before proceeding further let’s have a quick look at the solution to the above error.

Solution:

You should use an integer to access an element using its index.

But this brings us to a number of questions. Let’s have a look at them one by one.

â—ˆ What Is TypeError in Python?

TypeError is generally raised when a certain operation is applied to an object of an incorrect type.

Example:

Output:

TypeError: can only concatenate str (not “int”) to str

In the above code, we tried to add a string object and an integer object using the + operator. This is not allowed; hence we encountered a TypeError.

There can be numerous reasons that lead to the occurrence of TypeError. Some of these reasons are:

  • Trying to perform an unsupported operation between two types of objects.
  • Trying to call a non-callable caller.
  • Trying to iterate over a non-iterative identifier.

â—ˆ Reason Behind – TypeError: List Indices Must Be Integers Or Slices, Not ‘Str’

Python raises TypeError: List Indices Must Be Integers Or Slices, Not 'Str' whenever you try to access a value or an index of a list using a string.

Let us have a look at another complex example where you might encounter this kind of TypeError.

â—ˆ Example: Trying To Access A Value Of A List of Dictionaries Using A String

Problem: Given a list of dictionaries; Each dictionary within the list contains the name of an athlete and the sports he is associated with. You have to help the user with the sports when the user enters the athletes name.

Your Code:

Output:

Traceback (most recent call last):
File “D:/PycharmProjects/pythonProject1/TypeError part2.py”, line 25, in
if search.lower() in athletes[‘Name’].lower():
TypeError: list indices must be integers or slices, not str

Explanation: The above error occurred because you tried to access Name using the key. The entire data-structure in this example is a list that contains dictionaries and you cannot access the value within a particular dictionary of the list using it’s key.

Solution 1: Accessing Index Using range() + len()

To avoid TypeError: list indices must be integers or slices, not str in the above example you must first access the dictionary using it’s index within the list that contains the search value and then access the value using its key.

Output:

Explanation:

  • Instead of directly iterating over the list, you should iterate through each dictionary one by one within the list using the len() and range() methods.
  • You can access a particular value from a particular dictionary dictionary using the following syntax:
    • list_name[index_of_dictionary]['Key_within_dictionary']
    • example:- athletes[n]['name']

Solution 2: Accessing Index Using enumerate()

You can access the index of a dictionary within the list using Python’s built-in enumerate method as shown below.

Output:

Solution 3: Python One-Liner

Though this might not be the simplest of solutions or even the most Python way of resolving the issue but it deserves to be mentioned because it’s a great trick to derive your solution in a single line of code.

Solutions:

â—ˆ A Simple Example

In case you were intimidated by the above example, here’s another example for you that should make things crystal clear.

Problem: You have a list containing names, and you have to print each name with its index.

Your Code:

Output:

Solution:

In the above code the variable i represents an item inside the list and not an index. Therefore, when you try to use it as an index within the for loop it leads to a TypeError: list indices must be integers or slices, not str.

To avoid this error, you can either use the enumerate() function or the len() method along with the range() method as shown in the solution below.

Output:

Conclusion

We have come to the end of this comprehensive guide to resolve TypeError: List Indices Must Be Integers Or Slices, Not 'Str'. I hope this article helped clear all your doubts regarding TypeError: list indices must be integers or slices, not str and you can resolve them with ease in the future.

Please stay tuned and subscribe for more exciting articles. Happy learning! 📚

Was this post helpful?

Leave a Reply

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