List indices must be integers or slices not str как исправить

Мне нужно написать функцию, которая с помощью for проходит по списку и выводит название штата и количество букв в нем.

newEngland = ["Maine","New Hampshire","Vermont", "Rhode Island", 
"Massachusetts","Connecticut"]


def how_many_let(ne):
    lis=ne
    for i in lis:
        num_let=len(lis[i])
        print(i,' has',num_let,' letters')

Получаю ошибку:

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

Я не знаю, как исправить эту ошибку. Буду благодарна за любую помощь.

insolor's user avatar

insolor

45.7k16 золотых знаков54 серебряных знака95 бронзовых знаков

задан 22 авг 2017 в 5:55

Katerina Osmehovskaia's user avatar

4

Вы с помощью for проходите по списку lis, а список lis – это список строк. Соответственно, в i попадает строка, отсюда ошибка, что i (строку) нельзя использовать в качестве индекса (lis[i]). В вашем случае индексы вообще не нужны, просто учитывайте, что при проходе по списку вы получаете сами строки из списка, а не индексы:

def how_many_let(ne):
    lis=ne
    for word in lis:
        num_let=len(word)
        print(word, 'has', num_let, 'letters')

Еще пара моментов:

  1. Обратите внимание, что при присваивании lis=ne не происходит копирование списка. В принципе эта операция тут и не нужна, но зачем-то вы же ее вставили, поэтому на всякий случай предупреждаю)
  2. При выводе через print нескольких аргументов между ними автоматически вставляются пробелы. Дополнительные пробелы в строках 'has' и 'letters' в данном случае не нужны.

Если все-таки вдруг понадобятся еще и индексы строк, можно воспользоваться функцией enumerate:

for i, word in enumerate(lis):  # в word попадает строка из списка, а в i - ее индекс
    ...

ответ дан 22 авг 2017 в 6:15

insolor's user avatar

insolorinsolor

45.7k16 золотых знаков54 серебряных знака95 бронзовых знаков

2

SPISOK_GORODOV = ["Maine","New Hampshire","Vermont", "Rhode Island",
"Massachusetts","Connecticut"]

for GOROD in SPISOK_GORODOV:
    DLINA_GORODA=len(GOROD)
    print(GOROD, 'has', DLINA_GORODA, 'letters')

В вашем коде обрабатывается не индекс i, а конкретно каждый элемент списка, в данном случае строки. Похоже на то, что при написании этого цикла, вы руководствовались логикой других языков программирования.

ответ дан 23 сен 2017 в 11:26

Demuz Inc.'s user avatar

2


def count_letters(name):
    for one in name:
        name_len = len(one) - one.count(" ")  #кол-во букв в названии, не считая пробелы 
        print(f'{one} contains {name_len} letters in name')

newEngland = ["Maine","New Hampshire","Vermont", "Rhode Island","Massachusetts",
"Connecticut"]

count_letters(newEngland)

ответ дан 15 дек 2019 в 23:25

sQuality's user avatar

1

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.

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!

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']

Добавить комментарий