[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! 📚

Related Posts

  • Compare date in SQL
    08 October

    How to Compare Dates in SQL

    Table of ContentsAgendaIntroduction to DATE in SQLComparing Dates in SQL with ExamplesUsing Comparison OperatorsUsing the BETWEEN ClauseComparing Dates for DATETIME Datatypes/FormatsUsing Comparison Operator with TimeStampCasting DATETIME as DATE without TimestampUsing Between Clause with DATETIME Agenda This article will look at yet another interesting topic in SQL commonly asked in interviews – How to Compare Dates […]

  • Get Number of Elements in Array in C++
    08 October

    Get Number of Elements in Array in C++

    Table of ContentsGet Number of Elements in Array in C++Using the sizeof() functionUsing the pointersUsing the size() functionGet the frequency of each element in array in C++Using nested for loopUsing maps One of the most fundamental collections in any programming language is an array. It stores a similar type of data at specific indices that […]

  • can you screenshot onlyfans
    08 October

    Can You Screenshot OnlyFans? Here is Everything You Need to Know

    Table of ContentsOnlyFans: A Brief IdeaCan You Screenshot OnlyFans?Can You Screenshot OnlyFans Without Getting Banned?Can You Screenshot OnlyFans Without Them Knowing: Screenshot NotificationsFrequently Asked Questions About: Can You Screenshot OnlyFans?What Happens When You Try Taking OnlyFans Screenshots?Is Screenshotting Illegal?Do the OnlyFans screenshots lead to a permanent account ban?Can OnlyFans screenshots be detected?Wrapping Up Can you […]

  • Trust browser enable
    08 October

    How to enable trust wallet browser

    Table of ContentsTrust DApp Browser: A Brief OverviewWhat are DApps on Trust Wallet?Access DApps Using Trust Wallet: Easiest ApproachTrust Browser Enable on Android: How to Activate/Enable DApp Browser on Trust WalletTrust Browser Enable on iOS: How to Activate/Enable DApp Browser on Trust Wallet#Method 1: “Trust Browser Enable” Procedure#Method 2: Enabling DApp by Visiting Pancake SwapFrequently […]

  • how-to-find-someone-on-onlyfans
    07 October

    How to Find Someone on OnlyFans: Working Methods

    Table of ContentsHow to Find Someone on OnlyFansHow to Find Someone on OnlyFansHow to Find Someone on OnlyFans: The Official Username MethodThe OnlyFans TrickHow to Find Someone on OnlyFans: The Email MethodHow to Find Someone on OnlyFans: The OnlyFinder MethodHow to Find Someone on OnlyFans By Location (Map Feature)How to Find Someone on OnlyFans By […]

  • How to delete snapchat messages the other person saved
    07 October

    How to delete snapchat messages the other person saved

    Table of ContentsHow to delete Snapchat messages the other person saved#Step 1: Log in to Your Snapchat Account#Step 2: Navigate to the Desired Chat#Step 3: Unsave The Message from Your End#Step 4: Long-Press and Delete the Message#Step 5: Proceed with the Learn More option#Step 6: Click Okay#Step 7: Tap on the option that says “Delete.”How […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.