How To Fix TypeError: List Indices Must Be Integers Or Slices, Not ‘Str’?

✯ Overview

Problem: Fixing TypeError: list indices must be integers or slices, not str in Python.

Example: The following code lists a certain number of transactions entered by the user.

t = [5000, 1500, 10000, 20000, 6500, 8000, 9000, 15000, 2000, 16000]
n = input('Enter the Number of transactions you want to check: ')
for i in n:
    print(t[i])

Output:

Enter the Number of transactions you want to check: 5
Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/rough.py", line 4, in <module>
    print(t[i])
TypeError: list indices must be integers or slices, not str

Solution: Please go through this solution only after you have gone through the scenarios mentioned below.

t = [5000,1500,10000,20000,6500,8000,9000,15000,2000,16000]
n = input('Enter the Number of transactions you want to check: ')
for i in range(int(n)):
    print(t[i])

Bugs like these can be really frustrating! ? But, after you finish reading this article, these silly bugs will no longer be a matter of concern for you. Therefore, to understand what causes such errors and how to avoid them, it is important to answer a few questions:

  • What is a TypeError in Python?
  • Why does Python raise TypeError: list indices must be integers or slices, not str ?
  • How do we fix TypeError: list indices must be integers or slices, not str?

✯ What Is TypeError in Python?

Python raises a TypeError when you try to use a function or call an operator on something that is of the incorrect type.

There common reasons that are responsible for the occurrence of TypeError in Python are:

  • If you try to perform a certain operation that is not supported operation between two types of objects.
  • If you try to call a non-callable caller/function.
  • If you try to iterate over a non-iterative identifier.

Example:

radius = input("Enter the radius: ")  # string input
print('Circumference = ', 2 * 3.14 * radius)

Output:

Enter the radius: 5
Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/TypeError Can’t Multiply Sequence by non-int of Type ‘float’ In Python.py", line 2, in <module>
    print('Circumference = ',2*3.14*radius)
TypeError: can't multiply sequence by non-int of type 'float'

? Explanation: Python does not allow multiplication of a string value and a float value. Hence, when you try to perform this sort of unsupported operation in Python, it raises a TypeError.

That brings us to our next question!

✨ Why Does Python Raise TypeError: List Indices Must Be Integers Or Slices, Not ‘Str’?

? You can access items within sequential data-types like strings, tuples and lists using their index. Now, these indexes should always be integers. When you try to access the index of the list using a string value, then Python raises – TypeError: list indices must be integers or slices, not str.

Let us have a look at few examples to understand how to resolve this error.

✨ Example 1

Problem: The following program intends to assign a roll number to a student.

roll = [1, 2, 3, 4, 5]
name = ['Shubham', 'Chris', 'Yakun', 'Jesus', 'Krishna']
i = input("Enter roll no. : ")
print("Name: "+name[i-1]+"\nRoll: "+i)

Output:

Enter roll no. : 5
Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/rough.py", line 4, in <module>
    print("Name: "+name[i]+"\nRoll: "+i)
TypeError: list indices must be integers or slices, not str

Now, let us dive into the solutions.

? Solution: Accept User Input As An Integer

roll = [1, 2, 3, 4, 5]
name = ['Shubham', 'Chris', 'Yakun', 'Jesus', 'Krishna']
i = int(input("Enter roll no. : "))
print("Name: "+name[i-1]+"\nRoll: "+str(i))

Output:

Enter roll no. : 1
Name: Shubham
Roll: 1

Explanation:

To avoid a TypeError in the above scenario:

  • Accept the user input as an integer with the help of int() method.
  • Ensure that you concatenate values of the same data-type i.e. strings by with the help of str() method.

Now let us move on to a little more complex scenario.

✨ Example 2

Problem: Given a list of dictionaries; how to extract a certain value using it’s index?

people = [
    {'Name': 'Harry',
     'phone': '6589',
     'address': '90 Eastlake Court'
     },
    {
        'Name': 'Ben',
        'phone': '5693',
        'address': '560 Hartford Drive'
    },
    {
        'Name': 'David',
        'phone': '8965',
        'address': '96 SW 42nd'
    }
]
search = input('Enter the name of the person to find his address: ')
for n in (people):
    if search.lower() in people['Name'].lower():
        print('Name: ', search)
        print('Address: ', people['address'])
        break
else:
    print('Invalid Entry!')

Output:

Enter the name of the person to find his address: harry
Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/rough.py", line 19, in <module>
    if search.lower() in people['Name'].lower():
TypeError: list indices must be integers or slices, not str

➥ In the above example we tried to access the index using the key ‘Name' which is a string. Since you cannot access an index within a list using a string, hence Python raises TypeError: list indices must be integers or slices, not str.

Now let’s have a look at the solutions.

? Method 1: Using range() + len()

  • To access a particular index inside the list, you must find the length of the list using the len() method. This value will be an integer. Now you can use the range() upon the calculated length function to iterate over each element within the list.
  • Syntax to access a particular value from a particular dictionary within a list:
    • list_name[index_of_dictionary]['Key_within_dictionary']
    • example:- people[n]['name']
people = [
    {'Name': 'Harry',
     'phone': '6589',
     'address': '90 Eastlake Court'
     },
    {
        'Name': 'Ben',
        'phone': '5693',
        'address': '560 Hartford Drive'
    },
    {
        'Name': 'David',
        'phone': '8965',
        'address': '96 SW 42nd'
    }
]
search = input('Enter the name of the person to find his address: ')
for n in range(len(people)):
    if search.lower() in people[n]['Name'].lower():
        print('Name: ', people[n]['Name'])
        print('Address: ', people[n]['address'])
        break
else:
    print('Invalid Entry!')

Output:

Enter the name of the person to find his address: harry
Name:  Harry
Address:  90 Eastlake Court

? Method 2: Using enumerate()

➥ Pythons built-in enumerate(iterable) function allows you to loop over all elements in an iterable and their associated counters.

The following example demonstrates how Python’s built-in enumerate() method allows you to access the items of a dictionary within a list:

people = [
    {'Name': 'Harry',
     'phone': '6589',
     'address': '90 Eastlake Court'
     },
    {
        'Name': 'Ben',
        'phone': '5693',
        'address': '560 Hartford Drive'
    },
    {
        'Name': 'David',
        'phone': '8965',
        'address': '96 SW 42nd'
    }
]
search = input('Enter the name of the person to find his address: ')
for n, name in enumerate(people):
    if search.lower() in people[n]['Name'].lower():
        print('Name: ', people[n]['Name'])
        print('Address: ', people[n]['address'])
        break
else:
    print('Invalid Entry!')

Output:

Enter the name of the person to find his address: ben
Name:  Ben
Address:  560 Hartford Drive

? Solution 3: Using List Comprehension

This might not be the most Pythonic or the easiest of solutions but it’s a great trick and a quick hack to derive your solution in a single line of code.

people = [
    {'Name': 'Harry',
     'phone': '6589',
     'address': '90 Eastlake Court'
     },
    {
        'Name': 'Ben',
        'phone': '5693',
        'address': '560 Hartford Drive'
    },
    {
        'Name': 'David',
        'phone': '8965',
        'address': '96 SW 42nd'
    }
]
search = input('Enter the name of the person to find his address: ')
print(next((item for item in people if search.lower() in item["Name"].lower()), 'Invalid Entry!')['address'])

Output:

Enter the name of the person to find his address: harry
90 Eastlake Court

Conclusion

I hope this article helped you! ? Please stay tuned and subscribe for more exciting articles. Happy learning! ?

The Complete Guide to PyCharm
  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.

Join the PyCharm Masterclass now, and master PyCharm by tomorrow!

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!