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

Here’s a great article from The Crazy Programmer

In python, we can have many types of errors in our code. One of the most common errors is TypeError: list indices must be integers or slices, not str. In this article, we are going to see what causes this error and how can we fix this error.

This error mostly comes when we are working with lists in python. Whether we are printing the contents of a list or modifying any value at a particular position in the list. In this article, we will discuss some points to remember when working with lists so that the probability of occurring these types of errors will be much less.

Case 1:

# Declare a List
l1 = [10, 20, 30, 40, 50]

# Get Index input from User
index = input("Enter the Index at which you want to change value: ")

# Get the number from user
number = int(input("Enter the final value you want in list : "))

# Update the value in list
l1[index] = number

# Print the list after updation
print(f"Updated list is : {l1}")

Output:

PS C :  Users  ASUS  Desktop  Crazy Programmer Work > python -u " c :  Users  ASUS  Desktop  Crazy Programmer Work  test.py "
Enter the Index at which you want to change value: 3
Enter the final value you want in list : 76
Traceback (most recent call last):
  File "c :  Users  ASUS  Desktop  Crazy Programmer Work  test.py ", line 13, in <module>
    l1[index] = number
TypeError: list indices must be integers or slices, not str

In the above example, we have initialized a list of five numbers and we want to change the value of a particular index. We get out the index and value entered by the user and in the last operation, we are going to print the updated list. When we run the code and enter the respective value then we are getting the error. It states that the list indices must be integers or slices, not str it means that the index value we have passed in our code should be an integer.

We often make this mistake because we all know that the input function takes input as a string and if we want to use it as an integer then we have to convert it into an integer first, then we can use the index value and we will be able to perform our operation successfully.

Solution:

# Declare a List
l1 = [10, 20, 30, 40, 50]

# Get Index input from User and convert it to integer
index = int(input("Enter the Index at which you want to change value: "))

# Get the number from user
number = int(input("Enter the final value you want in list : "))

# Update the value in list
l1[index] = number

# Print the list after updation
print(f"Updated list is : {l1}")

Output:

PS C :  Users  ASUS  Desktop  Crazy Programmer Work > python -u " c :  Users  ASUS  Desktop  Crazy Programmer Work  test.py "
Enter the Index at which you want to change value: 3
Enter the final value you want in list : 76
Updated list is : [10, 20, 30, 76, 50]

As we can see that after converting the index value into an integer, we are successfully able to perform the desired operation. We can see that the value at 4th index has been changed to 76.

Case 2:

We are given with a list of words and we want to create a new string with all the words from the list and create a proper sentence and then print it.

# initialise a list of words
list1 = ["This", "article", "is", "written", "by", "crazy", "programmer"]

# initialise an empty string
new_string = ""

# initialist index with 0
index = 0

# run a loop through the list and add all the words in a string
while index < len(list1):
    new_string = new_string + " " + list1[new_string]
    index = index + 1

# print the new combined words
print(new_string)

When we run our code then we will get some error.

Output:

PS C :  Users  ASUS  Desktop  Crazy Programmer Work > python -u " c :  Users  ASUS  Desktop  Crazy Programmer Work  test.py "
Traceback (most recent call last):
  File "c :  Users  ASUS  Desktop  Crazy Programmer Work  test.py ", line 70, in <module>
    new_string = new_string + " " + list1[new_string]
TypeError: list indices must be integers or slices, not str

Here the same error occurred. It means we have to re examine the index value passed to the list in our program. We have to make sure that the index value should be in an integer only, to run our code perfectly. In line 70 we can see that the index we have passed to our list is a string. At this point, many programmers does not realize the mistake in the code and they spend 1 to 2 hours in debugging it. In our program, we know that new_string is a string so we cannot pass it as an index. We have identified the error.

Solution:

# initialize a list of words
list1 = ["This", "article", "is", "written", "by", "crazy", "programmer"]

# Initialize an empty string
new_string = ""

# initialize index with 0
index = 0

# run a loop through the list and add all the words in a string
while index < len(list1):
    new_string = new_string + " " + list1[index]
    index = index + 1

# print the new combined words
print(new_string)

Output:

PS C :  Users  ASUS  Desktop  Crazy Programmer Work > python -u " c :  Users  ASUS  Desktop  Crazy Programmer Work  test.py "
 This article is written by crazy programmer

We can see that our program is running successfully. We have fixed our code.

Conclusion

Whenever we see that error named TypeError: list indices must be integers or slices, not str. Then without making any changes in the code, firstly we have to figure out the uses of lists in our program, after that, we have to figure out where we are going to print the content of the lists or we are going to make any changes in the list.

If either of the cases is happening we have to check whether the index value passed in the list is an integer or not. It will give the error when the index value passed in the list is a string type. So we have to check it and fix it if it is not integer type.

The post Solve TypeError: list indices must be integers or slices, not str in Python appeared first on The Crazy Programmer.

Source link