ItsMyCode |
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 Python will raise TypeError: list indices must be integers or slices, not str exception.
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.
TypeError: list indices must be integers or slices, not str
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:\Personal\IJS\Code\main.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:\Personal\IJS\Code\program.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']
The post TypeError: list indices must be integers or slices, not str appeared first on ItsMyCode.
from Planet Python
via read more
No comments:
Post a Comment