List indices must be integers or slices not str python ошибка

This error occurs when using a string for list indexing instead of indices or slices. For a better understanding of list indexing, see the image below, which shows an example list labeled with the index values:
TypeError: list indices must be integers or slices, not str

This error occurs when using a string for list indexing instead of indices or slices. For a better understanding of list indexing, see the image below, which shows an example list labeled with the index values:

Using indices refers to the use of an integer to return a specific list value. For an example, see the following code, which returns the item in the list with an index of 4:

value = example_list[4] # returns 8

Using slices means defining a combination of integers that pinpoint the start-point, end-point and step size, returning a sub-list of the original list. See below for a quick demonstration of using slices for indexing. The first example uses a start-point and end-point, the second one introduces a step-size (note that if no step-size is defined, 1 is the default value):

value_list_1 = example_list[4:7]   # returns indexes 4, 5 and 6 [8, 1, 4]
value_list_2 = example_list[1:7:2] # returns indexes 1, 3 and 5 [7, 0, 1]

As a budding Pythoneer, one of the most valuable tools in your belt will be list indexing. Whether using indices to return a specific list value or using slices to return a range of values, you’ll find that having solid skills in this area will be a boon for any of your current or future projects.

Today we’ll be looking at some of the issues you may encounter when using list indexing. Specifically, we’ll focus on the error TypeError: list indices must be integers or slices, not str, with some practical examples of where this error could occur and how to solve it.

For a quick example of how this could occur, consider the situation you wanted to list your top three video games franchises. In this example, let’s go with Call of Duty, Final Fantasy and Mass Effect. We can then add an input to the script, allowing the user to pick a list index and then print the corresponding value. See the following code for an example of how we can do this:

favourite_three_franchises = ['Call of Duty', 'Final Fantasy', 'Mass Effect']

choice = input('Which list index would you like to pick (0, 1, or 2)? ')

print(favourite_three_franchises[choice])

Out:

Which list index would you like to pick (0, 1, or 2)?  0

Out:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-34186a0c8775> in <module>
      3 choice = input('Which list index would you like to pick (0, 1, or 2)? ')
      4 
----> 5 print(favourite_three_franchises[choice])

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

We’re getting the TypeError in this case because Python is detecting a string type for the list index, with this being the default data type returned by the input() function. As the error states, list indices must be integers or slices, so we need to convert our choice variable to an integer type for our script to work. We can do this by using the int() function as shown below:

favourite_three_franchises = ['Call of Duty', 'Final Fantasy', 'Mass Effect']

choice = int(input('Which list index would you like to pick (0, 1, or 2)? '))

print(favourite_three_franchises[choice])

Out:

Which list index would you like to pick (0, 1, or 2)?  1

Our updated program is running successfully now that 1 is converted from a string to an integer before using the choice variable to index the list, giving the above output.

Building on the previous example, let’s create a list of JSON objects. In this list, each object will store one of the game franchises used previously, along with the total number of games the franchise has sold (in millions). We can then write a script to output a line displaying how many games the Call of Duty franchise has sold.

favourite_three_franchises = [
  {
    "Name" : "Call of Duty", 
    "Units Sold" : 400
  },
  {
    "Name" : "Final Fantasy",
    "Units Sold" : 150
  },
  {
    "Name" : "Mass Effect",
    "Units Sold" : 16
  }
]

if favourite_three_franchises["Name"] == 'Call of Duty':
    print(f'Units Sold: {favourite_three_franchises["Units Sold"]} million')

Out:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-f61f169290d0> in <module>
     14 ]
     15 
---> 16 if favourite_three_franchises["Name"] == 'Call of Duty':
     17     print(f'Units Sold: {favourite_three_franchises["Units Sold"]} million')
TypeError: list indices must be integers or slices, not str

This error occurs because we have accidentally tried to access the dictionary using the "Name" key, when the dictionary is inside of a list. To do this correctly, we need first to index the list using an integer or slice to return individual JSON objects. After doing this, we can use the "Name" key to get the name value from that specific dictionary. See below for the solution:

for i in range(len(favourite_three_franchises)):
    if favourite_three_franchises[i]["Name"] == 'Call of Duty':
        print(f'Units Sold: {favourite_three_franchises[i]["Units Sold"]} million')

Out:

Units Sold: 400 million

Our new script works because it uses the integer type i to index the list and return one of the franchise dictionaries stored in the list. Once we’ve got a dictionary type, we can then use the "Name" and "Units Sold" keys to get their values for that franchise.

A slightly different cause we can also take a look at is the scenario where we have a list of items we’d like to iterate through to see if a specific value is present. For this example, let’s say we have a list of fruit and we’d like to see if orange is in the list. We can easily make the mistake of indexing a list using the list values instead of integers or slices.

fruit_list = ['Apple', 'Grape', 'Orange', 'Peach']

for fruit in fruit_list:
    if fruit_list[fruit] == 'Orange':
        print('Orange is in the list!')

Out:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-0a8aff303bb3> in <module>
      2 
      3 for fruit in fruit_list:
----> 4     if fruit_list[fruit] == 'Orange':
      5         print('Orange is in the list!')
TypeError: list indices must be integers or slices, not str

In this case, we’re getting the error because we’ve used the string values inside the list to index the list. For this example, the solution is pretty simple as we already have the list values stored inside the fruit variable, so there’s no need to index the list.

fruit_list = ['Apple', 'Grape', 'Orange', 'Peach']

for fruit in fruit_list:
    if fruit == 'Orange':
        print('Orange is in the list!')

Out:

Orange is in the list!

As you can see, there was no need for us to index the list in this case; the list values are temporarily stored inside of the fruit variable as the for statement iterates through the list. Because we already have the fruit variable to hand, there’s no need to index the list to return it.

For future reference, an easier way of checking if a list contains an item is using an if in statement, like so:

fruit_list = ['Apple', 'Grape', 'Orange', 'Peach']

if 'Orange' in fruit_list:
    print('Orange is in the list!')

Out:

Orange is in the list!

Or if you want the index of an item in the list, use .index():

idx = fruit_list.index('Orange')
print(fruit_list[idx])

Bear in mind that using .index() will throw an error if the item doesn’t exist in the list.

Summary

This type error occurs when indexing a list with anything other than integers or slices, as the error mentions. Usually, the most straightforward method for solving this problem is to convert any relevant values to integer type using the int() function. Something else to watch out for is accidentally using list values to index a list, which also gives us the type error.

Table of Contents

  • ◈ Overview
  • ◈ What Is TypeError in Python?
  • ◈ Reason Behind – TypeError: List Indices Must Be Integers Or Slices, Not ‘Str’
  • ◈ Example: Trying To Access A Value Of A List of Dictionaries Using A String
    • ✨ Solution 1: Accessing Index Using range() + len()
    • ✨ Solution 2: Accessing Index Using enumerate()
    • ✨ Solution 3: Python One-Liner
  • ◈ A Simple Example
  • Conclusion

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

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.

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

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 <module>

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

If you are accessing the elements of a list in Python, you need to access it using its index position or slices. However, if you try to access a list value using a string instead of integer to access a specific index Python will raise TypeError: list indices must be integers or slices, not str exception.

We can resolve the error by converting the string to an integer or if it is dictionary we can access the value using the format list_name[index_of_dictionary]['key_within_dictionary']

In this tutorial, we will learn what “list indices must be integers or slices, not str” error means and how to resolve this TypeError in your program with examples.

Lists are always indexed using a valid index number, or we can use slicing to get the elements of the list. Below is an example of indexing a list.

# Example 1: of list indexing
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print(my_list[5])

# Example 2: of list slicing
fruits = ["Apple", "Orange", "Lemon", "Grapes"]
print("Last 2 fruits is", fruits[2:4])

Output

6
Last 2 fruits is ['Lemon', 'Grapes']

The first example is we use an integer as an index to get the specific element of a list.

In the second example, we use a Python slicing technique by defining a start point and end-point to retrieve the sublist from the main list.

Now that we know how to access the elements of the list, there are several scenarios where developers tend to make mistakes, and we get a TypeError. Let us take a look at each scenario with examples.

Scenario 1: Reading string input from a user

It’s the most common scenario where we do not convert the input data into a valid type in Menu-driven programs, leading to TypeError. Let us take an example to reproduce this issue.

Consider an ATM menu-driven example where the user wants to perform certain operations by providing the input to the program.

menu = ["Deposit Cash", "Withdraw Case", "Check Balance", "Exit"]
choice = input(
    'Choose what would you like to perform (Valid inputs 0, 1, 2, 3)')
print(menu[choice])

Output

Choose what would you like to perform (Valid inputs 0, 1, 2, 3)2
Traceback (most recent call last):
  File "C:PersonalIJSCodemain.py", line 13, in <module>
    print(menu[choice])
TypeError: list indices must be integers or slices, not str

When the user inputs any number from 0 to 3, we get TypeError: list indices must be integers or slices, not str, because we are not converting the input variable “choice” into an integer, and the list is indexed using a string.

We can resolve the TypeError by converting the user input to an integer, and we can do this by wrapping the int() method to the input, as shown below.

menu = ["Deposit Cash", "Withdraw Case", "Check Balance", "Exit"]
choice = int(input(
    'Choose what would you like to perform (Valid inputs 0, 1, 2, 3) - ' ))
print(menu[choice])

Output

Choose what would you like to perform (Valid inputs 0, 1, 2, 3) - 2
Check Balance

Scenario 2: Trying to access Dictionaries list elements using a string

Another reason we get TypeError while accessing the list elements is if we treat the lists as dictionaries. 

In the below example, we have a list of dictionaries, and each list contains the actor and name of a movie.

actors = [
    {
        'name': "Will Smith",
        'movie': "Pursuit of Happiness"
    },

    {
        'name': "Brad Pitt",
        'movie': "Ocean's 11"
    },
    {
        'name': "Tom Hanks",
        'movie': "Terminal"
    },
    {
        'name': "Leonardo DiCaprio",
        'movie': "Titanic"
    },
    {
        'name': "Robert Downey Jr",
        'movie': "Iron Man"
    },
]

actor_name = input('Enter the actor name to find a movie -   ')
for i in range(len(actors)):
    if actor_name.lower() in actors['name'].lower():
        print('Actor Name: ', actors['name'])
        print('Movie: ', actors['movie'])
        break
else:
    print('Please choose a valid actor')

Output

Enter the actor name to find a movie -   Brad Pitt
Traceback (most recent call last):
  File "C:PersonalIJSCodeprogram.py", line 27, in <module>
    if actor_name.lower() in actors['name'].lower():
TypeError: list indices must be integers or slices, not str

We need to display the movie name when the user inputs the actor name.

When we run the program, we get TypeError: list indices must be integers or slices, not str because we are directly accessing the dictionary items using the key, but the dictionary is present inside a list. 

If we have to access the particular value from the dictionary, it can be done using the following syntax.

list_name[index_of_dictionary]['key_within_dictionary']

We can resolve this issue by properly iterating the dictionaries inside the list using range() and len() methods and accessing the dictionary value using a proper index and key, as shown below.

actors = [
    {
        'name': "Will Smith",
        'movie': "Pursuit of Happiness"
    },

    {
        'name': "Brad Pitt",
        'movie': "Ocean's 11"
    },
    {
        'name': "Tom Hanks",
        'movie': "Terminal"
    },
    {
        'name': "Leonardo DiCaprio",
        'movie': "Titanic"
    },
    {
        'name': "Robert Downey Jr",
        'movie': "Iron Man"
    },
]

actor_name = input('Enter the actor name to find a movie -   ')
for i in range(len(actors)):
    if actor_name.lower() in actors[i]['name'].lower():
        print('Actor Name: ', actors[i]['name'])
        print('Movie: ', actors[i]['movie'])
        break
else:
    print('Please choose a valid actor')

Output

Enter the actor name to find a movie -   Brad Pitt
Actor Name:  Brad Pitt
Movie:  Ocean's 11

Conclusion

The TypeError: list indices must be integers or slices, not str occurs when we try to index the list elements using string. The list elements can be accessed using the index number (valid integer), and if it is a dictionary inside a list, we can access using the syntax list_name[index_of_dictionary]['key_within_dictionary']

List indexing is a valuable tool for you as a Python developer. You can extract specific values or ranges of values using indices or slices. You may encounter the TypeError telling you that the index of the list must be integers or slices but not strings. In this part of Python Solutions, we will discuss what causes this error and solve it with several example scenarios.


Table of contents

  • Why Does This Error Occur?
  • Iterating Over a List
    • Solution
  • Incorrect Use of List as a Dictionary
    • Solution 1: Using range() + len()
    • Solution 2: Using enumerate()
    • Solution 3: Using Python One-Liner
  • Not Converting Strings
  • Summary

Why Does This Error Occur?

Each element in a list object in Python has a distinct position called an index. The indices of a list are always integers. If you declare a variable and use it as an index value of a list element, it does not have an integer value but a string value, resulting in the raising of the TypeError.

In general, TypeError in Python occurs when you try to perform an illegal operation for a specific data type.

You may also encounter the similar error “TypeError: list indices must be integers, not tuple“, which occurs when you try to index or slice a list using a tuple value.

Let’s look at an example of a list of particle names and use indices to return a specific particle name:

particle_list = ['gluon', 'photon', 'muon', 'electron', 'Z-boson']

value = particle_list[2]

print(value)
muon

You can also use slices, which define an integer combination: start-point, end-point, and step-size, which will return a sub-list of the original list. See the slice operation performed on the particle list:

sub_list_1 = particle_list[3:5]

print(sub_list_1)
['electron', 'Z-boson']
sub_list_2 = particle_list[1:5:2]

print(sub_list_2)
['photon', 'electron']

In the second example, the third integer is the step size. If you do not specify the step size, it will be set to the default value of 1.

Iterating Over a List

When trying to iterate through the items of a list, it is easy to make the mistake of indexing a list using the list values, strings instead of integers or slices. If you try iterating over the list of particles using the particle names as indices, you will raise the TypeError

particle_list = ['gluon', 'photon', 'muon', 'electron', 'Z-boson']

for particle in particle_list:
    if particle_list[particle] == 'electron':
        print('Electron is in the list!')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      1 for particle in particle_list:
      2     if particle_list[particle] == 'electron':
      3         print('Electron is in the list!')
      4 

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

Here, the error is raised because we are using string values as indices for the list. In this case, we do not need to index the list as the list values exist in the particle variable within the for statement.

Solution

particle_list = ['gluon', 'photon', 'muon', 'electron', 'Z-boson']

for particle in particle_list:
    if particle == 'electron':
        print('Electron is in the list!')
Electron is in the list!

We can use the if in statement to check if an item exists in a list as discussed in the Python: Check if String Contains a Substring. For example:

particle_list = ['gluon', 'photon', 'muon', 'electron', 'Z-boson']

if 'electron' in particle_list:
    print('Electron is in the list!')
Electron is in the list!

Incorrect Use of List as a Dictionary

We can treat the list of particle names to include their masses and store the values as a list of JSON objects. Each object will hold the particle name and mass. We can access the particle mass using indexing. In this example, we take the electron, muon and Z-boson:

 particles_masses = [
 {
"Name": "electron",
"Mass": 0.511
},
 {
"Name": "muon",
"Mass": 105.7
},
{
"Name": "Z-boson",
"Mass": 912000
}
]

if particles_masses["Name"] == 'muon':
    print(f'Mass of Muon is: {particles_masses["Mass"]} MeV')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      1 if particles_masses["Name"] == 'muon':
      2     print(f'Mass of Muon is: {particles_masses["Mass"]} MeV')
      3 

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

We see the error arise because we are trying to access the dictionary using the “Name” key, but the dictionary is actually inside a list. You must first access the dictionary using its index within the list.

Solution 1: Using range() + len()

When accessing elements in a list, we need to use an integer or a slice. Once we index the list, we can use the “Name” key to get the specific element we want from the dictionary.

for i in range(len(particles_masses)):
    if particles_masses[i]["Name"] == 'muon':
        print(f'Mass of Muon is: {particles_masses["Mass"]} MeV')
Mass of Muon is: 105.7 MeV

The change made uses integer type I to index the list of particles and retrieve the particle dictionary. With access to the dictionary type, we can then use the “Name” and “Mass” keys to get the values for the particles present.

Solution 2: Using enumerate()

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

for n, name in enumerate(particles_masses):

    if particles_masses[n]["Name"] == 'muon':

        print(f'Mass of Muon is: {particles_masses[n]["Mass"]} MeV')
Mass of Muon is: 105.7 MeV

Solution 3: Using Python One-Liner

A more complicated solution for accessing a dictionary is to use the search() function and list-comprehension

search = input("Enter particle name you want to explore:  ")

print(next((item for item in particles_masses if search.lower() in item ["Name"].lower()), 'Particle not found!'))
Enter particle name you want to explore:  muon
{'Name': 'muon', 'Mass': 105.7}

Not Converting Strings

You may want to design a script that takes the input to select an element from a list. The TypeError can arise if we are trying to access the list with a “string” input. See the example below:

particles_to_choose = ["electron", "muon", "Z-boson"]

chosen = input('What particle do you want to study? (0, 1, or 2)?')

print(particles_to_choose[chosen])
What particle do you want to study? (0, 1, or 2)?1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
1 print(particles_to_choose[chosen])

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

The error arises because the index returned by the input() function’s default, which is “string”. To solve this, we need to convert the input chosen to an integer type. We can do this by using the int() function:

particles_to_choose = ["electron", "muon", "Z-boson"]

chosen = int(input('What particle do you want to study? (0, 1, or 2)?'))

print(particles_to_choose[chosen])
What particle do you want to study? (0, 1, or 2)?1
muon

Summary

This TypeError occurs when you try to index a list using anything other than integer values or slices. You can convert your values to integer type using the int() function. You can use the “if… in” statement to extract values from a list of strings. If you are trying to iterate over a dictionary within a list, you have to index the list using either range() + len(), enumerate() or next().

If you are encountering other TypeError issues in your code, I provide a solution for another common TypeError in the article titled: “Python TypeError: can only concatenate str (not “int”) to str Solution“.

Thanks for reading to the end of this article. Stay tuned for more of the Python Solutions series, covering common problems data scientists and developers encounter coding in Python. If you want to explore educational resources for Python in data science and machine learning, go to the Online Courses Python page for the best online courses and resources. Have fun and happy researching!

If you are stuck in the python code with this error [ TypeError: list indices must be integers or slices, not str ]. You are not alone as a python developer most of us face this error every week. In this article, I will explain to you the reason for this error with its solution. So let’s start.

The only reason for this error is when we put the string in list subscript while accessing the list’s element. Let’s see a quick demo.

list indices must be integers not str example

list indices must be integers not str example

In the above example, we can see very clearly that we have created a list ( sample_list) which contains four-elements. Now when we tried to access its element “A” it shows the same error. In the next section, we will see its solution.

TypeError: list indices must be integers or slices, not str ( Fix/Solution) –

We can only access the list element directly with its position. As you can we that position must be a single integer or range of integers. Let’s see how.

sample_list=["A","B","C","D"]
element=sample_list[0]
print(element)

Here is the output for the above sample code.

list indices must be integers not str Fix

list indices must be integers, not str Fix

A list in python can contain any type of object in sequential form. It can we int, str, dictionaries (dict), other objects, or nested list, etc. A typical list starts from 0 indices.

Case studies for Python error[TypeError: list indices must be integers or slices, not str]-

Case 1:

if we have a list of python dictionaries and we want to compare a particular key of the dictionary with some variable.  Let’s see the below code.

sample_list=[{"dict1_key1":1, "dict1_key2":2},
             {"dict2_key1":3, "dict2_key2":4}]

if sample_list["dict2_key1"]==3:
  print("Found the value : condition match")

The above code will through the below output.

TypeError                                 Traceback (most recent call last)
 in ()
      2              {"dict2_key1":3, "dict2_key2":4}]
      3 
----> 4 if sample_list["dict2_key1"]==3:
      5   print("Found the value : condition match")

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

Here we need to iterate the list and look for the key in the corresponding dictionary. Lets the correct implementation:

sample_list=[{"dict1_key1":1, "dict1_key2":2},
             {"dict2_key1":3, "dict2_key2":4}]

for ele in range(len(sample_list)):
  if sample_list[ele].get("dict2_key1")==3:
    print("Found the value : condition match")

Above, We have iterated the list with int value. Below is the output for the correct implementation of list indices.

Found the value : condition match

Case 2:

When the index/ position is an integer but their declaration is wrong. Let’s see the case with a coding example.

index in list is str

the index in the list is str

In the above example, we are accessing the list element with the index. But we have already declared the index as str (string object). The correct implementation is below.


sample_list=["A","B","C","D"]
index=2
print(sample_list[index])

I hope the above cases are more than sufficient to explain to you the fix and cause of this error.

Thanks
Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

String indices must be integers or slices, not strings? What does this error mean? It’s a TypeError, which tells us that we are trying to perform an operation on a value whose type is not compatible with the operation. What’s the solution?

In this guide, we’re going to answer all of those questions. We’ll discuss what causes this error in Python and why it is raised. We’ll walk through an example scenario to help you figure out how to solve it. Without further ado, let’s begin!

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

The Problem: typeerror: list indices must be integers or slices, not str

Houston, we have a TypeError:

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

This error is raised when you try to access a value inside a list using a string value.

Items in lists are indexed using numbers. Consider the following list:

1 2 3 4 5
S t r i n g

To access values in this string, we can use index slicing. This is when you call a string followed by an index value to retrieve the character at that position:

example_string = "String"

print(example_string[0])

This code returns: S. Our code retrieves the character at the index position 0 in our list.

If you try to access a list using a letter, like “S”, an error will occur.

An Example Scenario

The error “typeerror: list indices must be integers or slices, not str” is commonly raised when you try to access an item in a list of JSON objects as if it were a list.

Consider the following code snippet:

students = [
	{
		"name": "Lisa Simpson",	
		"age": 8
	},
	{
		"name": "Janey Powell",
		"age": 9
	},
	{
		"name": "Ralph Wiggum",
		"age": 8
	}
]

to_find = input("Enter the name of the student whose age you want to find: ")

for s in students:
	if students["name"] == to_find:
		print("The age of {} is {}.".format(students["name"], students["age"]))

This code snippet finds the age of a particular student in a class. First, we have declared a list of students. This list stores each student as a JSON object.

Next, we ask the user to enter the name of the student whose age they want to find. Our program then iterates over each student in the list using a for loop to find the student whose name matches the one we have specified.

If that particular name is found, the age of the student is printed to the console. Otherwise, nothing happens.

Let’s try to run our code:

Traceback (most recent call last):
  File "main.py", line 19, in <module>
	if students["name"] == to_find:
TypeError: list indices must be integers or slices, not str

Oh no. It’s a TypeError!

The Solution

You can solve the error “typeerror: list indices must be integers or slices, not str” by making sure that you access items in a list using index numbers, not strings.

The problem in our code is that we’re trying to access “name” in our list of students:

This corresponds with no value because our list contains multiple JSON objects. To solve this problem, we’re going to use a range() statement to iterate over our list of students. Then, we’ll access each student by their index number:

for s in range(len(students)):
	if students[s]["name"] == to_find:
		print("The age of {} is {}.".format(students[s]["name"], students[s]["age"]))

To start, we have used a range statement. This will allow us to iterate over every student in our list. We’ve replaced every instance of “students[“key_name”]” with “students[s][“key_name”]”. This allows us to access each value in the list.

Let’s run our code and see what happens:

Enter the name of the student whose age you want to find: Lisa Simpson
The age of Lisa Simpson is 9.

Our code has successfully found the age of Lisa Simpson.

We access each value in the “students” list using its index number instead of a string. Problem solved!

Conclusion

The error “typeerror: list indices must be integers or slices, not str” is raised when you try to access a list using string values instead of an integer. To solve this problem, make sure that you access a list using an index number.

A common scenario where this error is raised is when you iterate over a list and compare objects in the list. To solve this error, we used a range() statement so that we could access each value in “students” individually.

Now you’re ready to solve this error like a Python expert!


list indices must be integers or slices, not str

is one of the most common Python typeerrors. A typeerror generally occurs when we mistake the property or functionality of an object or data type with some other object.

In this Python guide, we will walk through this Python error and discuss the reason for its occurrence and solution with examples. So let’s get started.

We will start with breaking the error statement and discussing what it is trying to tell us. The error statement »

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

» contain two messages separated with a colon »

:

«.

The

typeerror

is the error type that tells us we are performing some illegal operation on an object that it does not support. The

list indices must be integers or slices, not str

is the error message that specifies the actual error.


What does «list indices must be integers or slices, not str» means?

The first word of the error is

list

. This means the error is related to the

Python list

object. A Python list is a container of sequential data elements, and to access individual elements from the list, we can perform indexing. In indexing, we use the integer value inside the square bracket after the list variable name.


Example

mylist = [1,2,3,4]

#access first element 
print(mylist[0])

Every value present in the list has a unique index number, and as the list stores all its elements in sequential order, the index number starts from

0

up to

n-1

, where

n

is the total number of elements present in the list.


Reason of error

Now we know that the error belongs to the Python list, and the Python list stores its elements in sequential order, gives a unique index number to its elements, and all the index numbers are the integer value starting from 0 upto n-1.

But if we mistreat the integer index value of a list with a string digit, the Python interpreter throws the  type error called

list indices must be integers or slices, not str

.


Example

# create a list
my_list = [2,3,4,5,6,7,8]

# string index
index = "0"

# error
print(my_list[index])


Output

Traceback (most recent call last):
File "main.py", line 7, in <module>
print(my_list[index])
TypeError: list indices must be integers or slices, not str


Break Error Output

The error output shows that we have an error in

line 7

, which means with the

print(my_list[index])

statement. If we look at our code in line 7, there we are trying to print the first elements of the list

my_list

using the index value

"0"

.

But the list supports only integer index values, but in our program, our index value is a string. That’s why the Python interpreter threw the error. Now you know what actually the error message is trying to tell us. The message is very straightforward. It tells us that the passed index is not an integer or slice but a string value.


Solution

The solution for the error is pretty simple. We just need to look at the error code line and check if the index value is an integer or a string. We are receiving the error. This means the index value is a string, so now we need to change it to the integer value.


Example

# create a list
my_list = [2,3,4,5,6,7,8]

# integer index
index = 0

print(my_list[index]) # 2

We could have also converted the string index value to the integer using the Python int function.


Example

# create a list
my_list = [2,3,4,5,6,7,8]

# integer index
index = "0"

print(my_list[int(index)]) #2


Common Scenario

The most common scenario when you receive this error is when you ask the user to input the index number, and you forget to convert the entered number into an integer.


Example

# input index number from the user
index = input("Enter the index number: ")

my_list = [23,454,52,34,235,56,34]

print(my_list[index])


output

Enter the index number: 4
Traceback (most recent call last):
File "main.py", line 6, in <module>
print(my_list[index])
TypeError: list indices must be integers or slices, not str

The input() function accepts the input from the user as a string object. But when we want to access the list elements, we need the integer index value. So to convert the string number to an integer number, we can use the int() function.


Solution

# input index number from the user
index = int(input("Enter the index number: "))

my_list = [23,454,52,34,235,56,34]

print(my_list[index])


Output

Enter the index number: 4
235

The statement »

int(input("Enter the index number: "))

» will convert the user entered string number into Python integer value.


Conclusion

In this tutorial, we discussed one of the most common Python errors, «typeerror:

list indices must be integers

or slices, not str».  This error occurs in Python when you pass the string object as an index value to the list index when you try to access the list elements. The Python list also supports slicing in that also we need to pass the integer index value. If you pass the string object, you will receive the same error.

If you are getting this error and confused with your code, please comment down your code. We will try to solve it for you.


People are also reading:

  • Python ‘numpy.ndarray’ object is not callable Solution

  • Java vs Python

  • Python typeerror: ‘int’ object is not subscriptable Solution

  • Python vs Django

  • Python SyntaxError: unexpected EOF while parsing Solution

  • Python vs PHP

  • How to Play sounds in Python?

  • Lowercase in Python

  • What is a constructor in Python?

  • Python TypeError: ‘function’ object is not subscriptable Solution

Понравилась статья? Поделить с друзьями:
  • List index out of range как исправить ошибку
  • List index out of range python ошибка как исправить
  • List assignment index out of range python ошибка
  • List add error java
  • Liquibase exception databaseexception error no schema has been selected to create in