How to Resolve Python Error "TypeError: list indices must be integers or slices, not tuple"
The TypeError: list indices must be integers or slices, not tuple
is a specific error in Python indicating that you attempted to access an element or slice of a list using square brackets []
, but provided a tuple inside the brackets instead of the required integer index or slice object.
This guide explains the valid ways to index lists and provides clear solutions to fix this common indexing error.
Understanding Python List Indexing
Python lists are ordered sequences, and you access their elements using zero-based integer indices or slices within square brackets []
:
- Integer Index:
my_list[i]
retrieves the single element at indexi
(wherei=0
for the first element,i=1
for the second,i=-1
for the last, etc.).my_list = ['a', 'b', 'c', 'd']
print(my_list[0]) # Output: a
print(my_list[2]) # Output: c
print(my_list[-1]) # Output: d - Slice:
my_list[start:stop:step]
retrieves a new list containing a range of elements.my_list = ['a', 'b', 'c', 'd', 'e']
print(my_list[1:4]) # Output: ['b', 'c', 'd'] (index 1 up to, not including, 4)
print(my_list[:2]) # Output: ['a', 'b'] (from start up to index 2)
print(my_list[3:]) # Output: ['d', 'e'] (from index 3 to the end)
The TypeError ... not tuple
occurs because Python doesn't allow you to put a tuple directly inside the brackets for standard list indexing.
Cause 1: Incorrect Syntax for Indexing (e.g., my_list[0, 1]
)
This is the most direct cause – using a comma-separated sequence inside the square brackets. Python interprets 0, 1
inside []
as a tuple literal (0, 1)
.
Error Scenario
my_list = ['w', 'x', 'y', 'z']
nested_list = [['a', 'b'], ['c', 'd']]
try:
# ⛔️ TypeError: list indices must be integers or slices, not tuple
# Python sees [0, 1] as indexing with the tuple (0, 1)
element = my_list[0, 1]
print(element)
except TypeError as e:
print(f"Error accessing my_list: {e}")
try:
# ⛔️ TypeError: list indices must be integers or slices, not tuple
# Trying to access nested element with tuple index
nested_element = nested_list[0, 1]
print(nested_element)
except TypeError as e:
print(f"Error accessing nested_list: {e}")
Solution: Use Single Integer Indices
Access elements one at a time using their integer index.
my_list = ['w', 'x', 'y', 'z']
print(f"Element at index 0: {my_list[0]}") # Output: Element at index 0: w
print(f"Element at index 1: {my_list[1]}") # Output: Element at index 1: x