Working with lists and indices can be confusing to new programmers learning Python. When accessing the elements of the list using indices, people often forget that they can only provide integer values to access and end up providing a tuple which causes them to encounter the error in question “Python error: list indices must be integers or slices, not a tuple.”
This post will guide you through the reason why you get this error and how to avoid it as well, and for this, let’s start with a demonstration of the error.
The “Python error: list indices must be integers or slices, not a tuple” Error
To demonstrate this error, create a new list using the following line in Python:
After that, assume that the user wants to access the values at index 1 and 4. Now, the user tries passing both of these index values in the square brackets separated by a comma like this:
The following output is shown on the terminal when the user execute the program:
Let’s see how to fix/avoid this error.
Solution 1: Accessing Separate Elements
If the goal of the user is to access separate elements placed at different index values, then the solution to avoid this error is to use separate bracket notions to access each element. Continuing the above example, to access the values placed at index 1 and index 2, the user can use the following approach:
Executing this code will produce the following output:
With this approach, you have successfully avoided the error.
Solution 2: Accessing a Range of Elements With Indexes
If the goal of the user is to access multiple elements in between certain index values, then instead of passing a tuple, the user can use slices. To use slices, the user needs to place a colon “:” in between the different index values.
Continuing the scenario mentioned above, if the user wants to print the elements between index 1 and 5, then the user can use the following command:
This will show the following output on the terminal:
The output shows the user got the required output without encountering the error.
The error “Python error: list indices must be integers or slices, not a tuple” is caused when the user tries to access the elements of an array but places a comma in between the index values instead of a colon. To avoid this error, the user can access separate elements by using separate bracket notation or provide a range (slice) by using a colon.