Last updated: Apr 8, 2024
Reading timeยท4 min
The Python "TypeError: list indices must be integers or slices, not tuple" occurs when we pass a tuple between the square brackets when accessing a list at index.
To solve the error, make sure to separate nested list elements with commas and correct the index accessor.
Here is one example of how the error occurs.
# โ๏ธ TypeError: list indices must be integers or slices, not tuple my_list = [['a', 'b']['c', 'd']] # ๐๏ธ Forgot a comma between elements
We forgot to separate the items in a two-dimensional list with a comma.
To solve the error, add a comma between the elements of the list.
# โ Works my_list = [['a', 'b'], ['c', 'd']] print(my_list)
All elements in a list must be separated by a comma.
You might also get the error if you use an incorrect index accessor.
my_list = [['a', 'b'], ['c', 'd']] # โ๏ธ TypeError: list indices must be integers or slices, not tuple result = my_list[0, 0]
my_list[2]
) or a slice (e.g. my_list[0:2]
) for list indices.my_list = ['a', 'b', 'c', 'd'] print(my_list[2]) # ๐๏ธ 'c' print(my_list[1:3]) # ๐๏ธ ['b', 'c']
If you need to get a value from a two-dimensional list, access the nested list using square brackets and use square brackets again to access the specific element.
my_list = [['a', 'b'], ['c', 'd']] print(my_list[0][0]) # ๐๏ธ 'a' print(my_list[0][1]) # ๐๏ธ 'b'
We access the first list (index 0
) with the first set of square brackets and
then access the nested list at the specified index.
Python indexes are zero-based, so the first item in a list has an index of 0
,
and the last item has an index of -1
or len(a_list) - 1
.
If you need to get a slice of a list, use a colon to separate the start and end indices.
my_list = ['a', 'b', 'c', 'd', 'e'] print(my_list[0:3]) # ๐๏ธ ['a', 'b', 'c'] print(my_list[3:]) # ๐๏ธ ['d', 'e']
The syntax for list slicing is
a_list[start:stop:step]
.
The start
index is inclusive and the stop
index is exclusive (up to, but not
including).
If the start
index is omitted, it is considered to be 0
, if the stop
index
is omitted, the slice goes to the end of the list.
If you need to access multiple, not-consecutive list items, access them separately.
my_list = ['a', 'b', 'c', 'd', 'e'] first = my_list[0] print(first) # ๐๏ธ 'a' second = my_list[1] print(second) # ๐๏ธ 'b'
numpy
arrayIf you use numpy
and are trying to access a nested list with two indices, make
sure to convert the list to a numpy
array first.
import numpy as np my_list = [['a', 'b'], ['c', 'd'], ['e', 'f']] arr = np.array(my_list) result = arr[:, 0] print(result) # ๐๏ธ ['a', 'c', 'e'] print(arr[0, 1]) # ๐๏ธ b print(arr[1, 1]) # ๐๏ธ d print(arr[2, 1]) # ๐๏ธ f
We used the numpy.array()
method to convert a list to a numpy
array.
The first example shows how to get the first item from each nested list in the array.
If you use numpy
, you can access a numpy
array at multiple indices directly.
import numpy as np arr = np.array(['bobby', 'hadz', 'com', 'a', 'b', 'c']) indices = [0, 2, 4] new_list = list(arr[indices]) print(new_list) # ๐๏ธ ['bobby', 'com', 'b']
We used the numpy.array() method to create a NumPy array and then accessed it directly at multiple indices.
If you need to install NumPy, run the following command from your terminal.
pip install numpy # ๐๏ธ or pip3 pip3 install numpy
If you need to iterate over a list, use a for
loop.
list_of_dicts = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bobby'}, {'id': 3, 'name': 'Carl'}, ] for item in list_of_dicts: print(item['id']) print(f'Name: {item["name"]}')
The example iterates over a list of dictionaries.
If you need to access the index of the current iteration when looping, use the
enumerate()
method.
my_list = ['bobby', 'hadz', 'com'] for index, item in enumerate(my_list): print(index, item) # ๐๏ธ 0 bobby, 1 hadz, 2 com
The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.
Make sure you aren't assigning a tuple to a variable by mistake.
my_list = ['a', 'b', 'c', 'd', 'e'] my_tuple = 0, 1 # โ๏ธ TypeError: list indices must be integers or slices, not tuple result = my_list[my_tuple]
In case you declared a tuple by mistake, tuples are constructed in multiple ways:
()
creates an empty tuplea,
or (a,)
a, b
or (a, b)
tuple()
constructorIf you aren't sure what type of object a variable stores, use the type()
class.
my_list = ['a', 'b', 'c', 'd', 'e'] print(type(my_list)) # ๐๏ธ <class 'list'> print(isinstance(my_list, list)) # ๐๏ธ True my_tuple = 0, 1 print(type(my_tuple)) # ๐๏ธ <class 'tuple'> print(isinstance(my_tuple, tuple)) # ๐๏ธ True
The type class returns the type of an object.
The isinstance() function
returns True
if the passed-in object is an instance or a subclass of the
passed-in class.