Fix Python TypeError: List Indices must be Integers or Slices, not str | CodingGear (2024)

If you come across an error like this: TypeError: list indices must be integers or slices, not str? Do not worry, it is just hinting that you have used the wrong data type (in this case, a string) as an index of a list item, instead of using an integer. Let me explain a little bit about what this means, then we will get into the details of how to fix it.

Fix Python TypeError: List Indices must be Integers or Slices, not str | CodingGear (1)

When Does the TypeError: list indices must be integers or slices, not str happen.

So, Each list item in a Python list has an index. An index is a number that represents the position of a list item in a list. It’s sort of like an identification number (ID). We usually use these index values to select a list item in a list or a sequence of list items from the list. The first list item in a list has an index of 0 (zero) and the next 1 and so on and so forth till the last item in the list.

Index0123
List Item'Steve'18{
'age': 18,
'name': 'Steve'
}
500

As you can see, all these indices are purely integers that return <class 'int'> when passed in the type() function. When we use any other data type other than an integer to select an item from a list, that’s when we get the error: TypeError: list indices must be integers or slices, not str. In this post, I will show you how to fix this error.

Fix Python TypeError: List Indices must be Integers or Slices, not str | CodingGear (2)

Check out my blog post on how to check if a list is empty in Python.

Then, you may also be asking, we have only covered integers as the only required datatype for selecting list items from a list, what about the ‘slices’ part that is also present in the error? Well, slices are also made up of integers and instead of selecting only one list item from the list; slices select a range of list items.

How to fix TypeError: list indices must be integers or slices, not str.

When thelist indices must be integers or slices, not str error occurs, it mentions some valuable information we can use to quickly locate where the error has happened therefore quickly solving it. Let’s take a look at an example:

Traceback (most recent call last): ➊File "file.py", ➋line 5, in <module> ➌print(error_words[first_word])TypeError: list indices must be integers or slices, not str

As you can tell, at ➊ Python mentions the file that the error has occurred, and at ➋ the line that is causing the error and below that at ➌, it even shows you the very line that is causing the error.

Using the information provided in the error itself, and the ways to solve the error that I will share with you in this post, you can quickly solve thelist indices must be integers or slices, not str error. Let’s see how to do that.

The TypeError: list indices must be integers or slices, not str usually happens because of one of the following things.

1. Fix TypeError: list indices must be integers or slices, not str when string variables are left unconverted.

The most common occurrence of the list indices must be integers or slices, not str error usually happens when we try to index a list item with a string not an integer. But this also does not happen in a straightforward manner. It involves using a variable that holds a string value as a list item index. Let’s take a look at the example below.

error_words = ['list', 'indices', 'must', 'integers', 'slices', 'not', 'str']first_word_index = '0'print(error_words[first_word_index])
Traceback (most recent call last): File "main.py", line 5, in <module> print(error_words[first_word_index])TypeError: list indices must be integers or slices, not str

The way to fix this TypeError: list indices must be integers or slices, not str when string variables are left unconverted is to convert the string that is holding the list index into an integer. We can do this programmatically by using the int() function. But manually, we can fix it just by removing the quotes from the string. Let’s take a look at the following example:

error_words = ['list', 'indices', 'must', 'integers', 'slices', 'not', 'str']first_word_index = '0' 👇 #use int() to cast str to intprint(error_words[int(first_word_index)])

2. Fix TypeError: list indices must be integers or slices, not str when working with a list of Dictionaries.

The next popular occurrence of the list indices must be integers or slices, not str error occurs mostly to beginners when they are working with a list of dictionaries. It happens in the same fashion as the previous one in that a string value is used as a list item index. But in this case, the confusion comes from treating lists like dictionaries.

We know that a dictionary is made up of key-value pairs and we use the key – which is usually a string but can also be an integer – to reference a dictionary. When we have a list of dictionaries, each dictionary in that list is a list item so it has its own index. In order to select a key that is in a dictionary inside a list, we should start by referencing the list item index first, then we can refer to the key in that dictionary. Most people will skip this part, and when they do, they are likely to get the classic TypeError: list indices must be integers or slices, not str. Let’s take a look at an example:

Case 1: When referencing a dictionary that is in a list

actors = [ { 'name': 'Tom Cruise', 'age': 60 }, { 'name': 'Arnold Schwarzenegger', 'age': 75 }, { 'name': 'Adam Sandler', 'age': 56 },]if actors['name'] == 'Adam Sandler': print('He is a genius')
Traceback (most recent call last): File "main.py", line 16, in <module> if actors['name'] == 'Adam Sandler':TypeError: list indices must be integers or slices, not str

I get the list indices must be integers or slices, not str here because I have tried to access a dictionary value using a key the same way I would have done with a list. But, which key-value pair am I trying to access here? Remember each dictionary in the actors list is a list item. Therefore, If I know which dictionary I want to select, I will use its index. Here is the solution.

if actors[2]['name'] == 'Adam Sandler': print('He is a genius')

Case 2: When looping over a list of dictionaries

Another mistake happens when looping over a list of dictionaries.

for actor in actors: name = actors['name'] age = actors['age'] print(f'{name} is {age} years old')
Traceback (most recent call last): File "main.py", line 17, in <module> name = actors['name']TypeError: list indices must be integers or slices, not str

Solution

for actor in actors: name = actor['name'] age = actor['age'] print(f'{name} is {age} years old')

Conclusion: Fix List Indices must be Integers or Slices, not str

If you have come across an error like TypeError: list indices must be integers or slices, not str? Do not worry, it is just hinting that you have used the wrong data type as an index of a list item. Usually, a string when you are supposed to be using an integer. There are other related errors like list indices must be integers or slices, not tuple, list indices must be integers or slices not float, which can be solved in the same way we have done the one we were solving in this post. Always make sure you use the help of information provided in the error to check the file and the line where the error has occurred.

I’ll see you in other related posts. Peace!

Fix Python TypeError: List Indices must be Integers or Slices, not str

Fix Python TypeError: List Indices must be Integers or Slices, not str | CodingGear (2024)

FAQs

Fix Python TypeError: List Indices must be Integers or Slices, not str | CodingGear? ›

This error generally occurs whenever we try to access the list using indexes but give strings instead of integers or slices in place of either the start point, end point, or step value. The most common solution to this problem is explicitly typecasting the index to an integer.

What does list indices must be integers or slices not integer? ›

The Python "TypeError: list indices must be integers or slices, not str" occurs when we use a string instead of an integer to access a list at a specific index. To solve the error, use the int() class to convert the string to an integer, e.g. my_list[int(my_str)] .

What does list integers must be indices or slices? ›

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.

What error occurs when a list value is accessed using a string instead of an integer? ›

These indexes are always defined using integers. You might declare a variable that has the index value of a list element. But if this variable does not have an integer value and instead has a string value, you will face an error called “TypeError: list indices must be integers or slices, not str”.

What error slice indices must be integers or none or have an __index __ method? ›

The “TypeError: slice indices must be integers or None or have an __index__ method” error is raised when you try to slice a list using a value that is not an integer, such as a float. To solve this error, make sure any values you use in a slicing statement are integers.

How do you fix string indices must be integers in Python? ›

The 'string indices must be integers' error in Python occurs when you're trying to access a character in a string using a non-integer index. To fix this error, you need to make sure that you're using an integer value for the index.

How do you turn a list back into a string in Python? ›

How to Convert List to String in Python?
  1. 1) Iterating through the List. This method will iterate every index of the input list one by one and add it to the empty string. ...
  2. 2) Using join() method. ...
  3. 3) Using List Comprehension. ...
  4. 4) Using map() function. ...
  5. 5) Using Enumerate Function. ...
  6. 6) Using functools. ...
  7. 7) Using str.
Jun 8, 2023

How to do a list of integers Python? ›

Convert the number to a list of integers by using the list comprehension: Convert the number to a string using str() function. Iterate over each character in the string using a for loop. Convert each character back to an integer using the int() function.

How do you check if it is integer in Python list? ›

Python offers isnumeric() method that checks whether a string is an integer or not. This method is similar to the isdigit() method but with a few differences. The isnumeric() method checks whether all the characters in the string are numeric. While the isdigit() method checks whether the strings contain only digits.

What are list indices in Python? ›

In Python, indexing refers to the process of accessing a specific element in a sequence, such as a string or list, using its position or index number. Indexing in Python starts at 0, which means that the first element in a sequence has an index of 0, the second element has an index of 1, and so on.

What does list indices must be integers or slices not float? ›

The “TypeError: list indices must be integers or slices, not float” error occurs when you try to access an item from a list using a floating-point number. To solve this error, make sure you only use integers to access items in a list by their index value.

What does list indices must be integers or slices not float mean? ›

The Python TypeError: list indices must be integers or slices, not float occurs when you attempt to access a list item using a number with floating points. To fix this error, you can convert the floating number to an integer using the int() function or use a slice to access a range of elements in the list.

What does list indices must be integers or slices not tuple? ›

The “TypeError: list indices must be integers, not tuple” error occurs when you specify a tuple as an index value at the end of a list. To solve this problem, make sure that any lists in a list of lists are separated using commas.

What does string indices must be integers mean? ›

All the characters of a string have a unique index . This index specifies the position of each character of the string. TypeError: string indices must be integers means an attempt to access a location within a string using an index that is not an integer. For example, str[hello"] and str[2.1] as indexes.

Top Articles
Latest Posts
Article information

Author: Twana Towne Ret

Last Updated:

Views: 6513

Rating: 4.3 / 5 (44 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Twana Towne Ret

Birthday: 1994-03-19

Address: Apt. 990 97439 Corwin Motorway, Port Eliseoburgh, NM 99144-2618

Phone: +5958753152963

Job: National Specialist

Hobby: Kayaking, Photography, Skydiving, Embroidery, Leather crafting, Orienteering, Cooking

Introduction: My name is Twana Towne Ret, I am a famous, talented, joyous, perfect, powerful, inquisitive, lovely person who loves writing and wants to share my knowledge and understanding with you.