Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

[Solved] 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.

list1 = ['Mathematics','Physics', 'Computer Science']
index = '1'
print('Second Subject: ', list1[index])

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.

list1 = ['Mathematics','Physics', 'Computer Science']
index = 1
print('Second Subject: ', list1[index])

# Output:-
# First Subject:  Physics

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:

print('Java'+2+'Blog')

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:

athletes = [
        {
            'name': "Mike Tyson",
            'sports': "Boxing"
        },
        {
            'name': "Pele",
            'sports': "Football"
        },
        {
            'name': "Sachin Tendulkar",
            'sports': "Cricket"
        },
        {
            'name': "Michael Phelps",
            'sports': "Swimming"
        },
        {
            'name': "Roger Federer",
            'sports': "Tennis"
        }
]
search = input('Enter the name of the athlete to find his sport: ')
for n in range(len(athletes)):
    if search.lower() in athletes['Name'].lower():
        print('Name: ',athletes['Name'])
        print('Sports: ', athletes['Name'])
        break
else:
    print('Invalid Entry!')

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.

athletes = [
        {
            'name': "Mike Tyson",
            'sports': "Boxing"
        },
        {
            'name': "Pele",
            'sports': "Football"
        },
        {
            'name': "Sachin Tendulkar",
            'sports': "Cricket"
        },
        {
            'name': "Michael Phelps",
            'sports': "Swimming"
        },
        {
            'name': "Roger Federer",
            'sports': "Tennis"
        }
]
search = input('Enter the name of the athlete to find his sport: ')
for n in range(len(athletes)):
    if search.lower() in athletes[n]['name'].lower():
        print('Name: ',athletes[n]['name'])
        print('Sports: ', athletes[n]['sports'])
        break
else:
    print('Invalid Entry!')

Output:

Enter the name of the athlete to find his sport: Sachin
Name:  Sachin Tendulkar
Sports:  Cricket

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.

athletes = [
        {
            'name': "Mike Tyson",
            'sports': "Boxing"
        },
        {
            'name': "Pele",
            'sports': "Football"
        },
        {
            'name': "Sachin Tendulkar",
            'sports': "Cricket"
        },
        {
            'name': "Michael Phelps",
            'sports': "Swimming"
        },
        {
            'name': "Roger Federer",
            'sports': "Tennis"
        }
]
search = input('Enter the name of the athlete to find his sport: ')
for n,name in enumerate(athletes):
    if search.lower() in athletes[n]['name'].lower():
        print('Name: ',athletes[n]['name'])
        print('Sports: ', athletes[n]['sports'])
        break
else:
    print('Invalid Entry!')

Output:

Enter the name of the athlete to find his sport: Tyson
Name:  Mike Tyson
Sports:  Boxing

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.

athletes = [
        {
            'name': "Mike Tyson",
            'sports': "Boxing"
        },
        {
            'name': "Pele",
            'sports': "Football"
        },
        {
            'name': "Sachin Tendulkar",
            'sports': "Cricket"
        },
        {
            'name': "Michael Phelps",
            'sports': "Swimming"
        },
        {
            'name': "Roger Federer",
            'sports': "Tennis"
        }
]

search = input('Enter the name of the athlete to find his sport: ')
print(next((item for item in athletes if search.lower() in item["name"].lower()), 'Invalid Entry!'))

Solutions:

Enter the name of the athlete to find his sport: Roger
{'name': 'Roger Federer', 'sports': 'Tennis'}

◈ 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:

li = ["John", "Rock", "Brock"]
i = 1
for i in li:
    print(i, li[i])

Output:

Traceback (most recent call last):
  File "D:/PycharmProjects/pythonProject1/TypeError part2.py", line 4, in 
    print(i, li[i])
TypeError: list indices must be integers or slices, not str

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.

li = ["John", "Rock", "Brock"]
print("***SOLUTION 1***")
# using range()+len()
for i in range(len(li)):
    print(i + 1, li[i])
print("***SOLUTION 2***")
# using enumerate()
for i, item in enumerate(li):
    print(i + 1, item)

Output:

***SOLUTION 1***
1 John
2 Rock
3 Brock

***SOLUTION 2***
1 John
2 Rock
3 Brock

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!



This post first appeared on How To Learn Java Programming, please read the originial post: here

Share the post

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

×

Subscribe to How To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×