The exception or error message TypeError: list indices must be integers or slices, not str shows up because a list object can only be accessed with an integer index and not by a string index. The exception type is TypeError because the index str is incorrect. The correct index type has to be int. To resolve the “TypeError: list indices must be integers or slices, not str,” you need to ensure that you use integer values or slices when accessing list elements. In this article, we will discuss this exception and how to avoid it.
1. What is the problem?
Let us dissect the exception message TypeError: list indices must be integers or slices, not str.
- TypeError – It is an exception class that tells us there is an error in the code related to the type of the object and the operator used on the object.
- list – A data type that stores sequences of objects. Example, forest_types = [‘temperate’, ‘tropical’, ‘boreal’].
- indices – Plural of index. This is used to extract value on a list based on index number.
- integers – An int data type, such as x = 0, y = 45, or z = -50.
- slices – A slice data type such as myslicer = slice(0, 4).
- str – An str data type, such as color = ‘blue’.
Let us look at the list, index, and how to get the list value by index.
1.1. A list of str
code
# Define a list str objects. players = ['Capablanca', 'Fischer', 'Kasparov', 'Carlsen'] # Get the players object type. print(f'players type is {type(players)}') # Print the list values by index. print(f'player at index 0 is {players[0]}') print(f'player at index 1 is {players[1]}') print(f'player at index 2 is {players[2]}') print(f'player at index 3 is {players[3]}')
output
players type is <class 'list'> player at index 0 is Capablanca player at index 1 is Fischer player at index 2 is Kasparov player at index 3 is Carlsen
A list can also be a list of int, float, list, dict and tuple.
1.2. A list of int
temperatures = [25, 45, -10, 15]
1.3. A list of float
heights = [1.5, 1.7, 1.82]
1.4. A list of list
height_weight = [[1.75, 70], [1.65, 68]]
1.5. A list of dict
peaceful_countries_capital = [{'Iceland': 'Reyjavik'}, {'New Zealand': 'Wellington'}, {'Ireland': 'Dublin'}]
What is the value at index 2?
print(peaceful_countries_capital[2]) # {'Ireland': 'Dublin'}
What are the top 2 countries?
We use slice object to get the top countries.
peaceful_countries_capital = [{'Iceland': 'Reyjavik'}, {'New Zealand': 'Wellington'}, {'Ireland': 'Dublin'}] slicer = slice(0, 2) print(peaceful_countries_capital[slicer]) # [{'Iceland': 'Reyjavik'}, {'New Zealand': 'Wellington'}]
1.6. A list of tuple
prog_lang = [('python', 'javascript'), ('c', 'cplusplus')]
1.7. Reproduce the error message
Now let us try to reproduce the error message TypeError: list indices must be integers or slices, not str.
In the following code, get the value at index 1.
code
players = ['Capablanca', 'Fischer', 'Kasparov', 'Carlsen'] print(players['1'])
output
Traceback (most recent call last): File "f:\Project\kodlogs\art6.py", line 3, in <module> print(players['1']) TypeError: list indices must be integers or slices, not str
Caution: TypeError: ‘TypeError: list indices must be integers or slices, not str
We successfully duplicated the error message. This is because we use an str index ‘1’. Python does not support this. The index must be of type int.
Tip: The index of a list starts at zero.
1.8. Practical example
Build a program and ask the user to input a number as index to extract the value at specific list index.
code
temperatures = [25, 45, -10, 15] def main(): # Ask the user. i = input('Input index number [0 to 3]? ') print(f'temperature at index {i} is {temperatures[i]}') if __name__ == '__main__': main()
output
Input index number [0 to 3]? 0 Traceback (most recent call last): File "f:\Project\kodlogs\art6.py", line 8, in <module> main() File "f:\Project\kodlogs\art6.py", line 5, in main print(f'temperature at index {i} is {temperatures[i]}') TypeError: list indices must be integers or slices, not str
Why we have this error? That means the variable i is an str and not an int or integer. The built-in function input returns an str type. In the next section, we will discuss how to deal with it.
2. Solution: How to avoid this error?
To avoid this type of exception, we need to know the type of the index. The type of index should be int. Look at the following example.
heights = [1.5, 1.7, 1.82]
To extract the value of the list at index 0, use the integer 0 and not the string ‘0’.
Correct
heights[0] # 1.5
Incorrect
heights['0'] # error
Let us go back to our previous practical example from section 1.
code
temperatures = [25, 45, -10, 15] def main(): # Ask the user. i = input('Input index number [0 to 3]? ') print(f'temperature at index {i} is {temperatures[i]}') if __name__ == '__main__': main()
Here the type of i is str. Since it is an integer string, we can convert that to int using the built-in function int()
i = input('Input index number [0 to 3]? ') i = int(i) # Convert str to int
With i in int type, we can now use the index without error such as temperatures[i].
If you are not sure of the index type, use the built-in function isinstance.
code
res = some_function() if isinstance(res, int): print('res is an integer')
3. Conclusion
We will encounter the exception message TypeError: list indices must be integers or slices, not str if we try to extract a value from the list using a str index. The correct type of index should be int. If you are not sure about the index type, use the isinstance() built-in function.