TypeError: list indices must be integers or slices not tuple


Borislav Hadzhiev

4 min


Photo from Unsplash

# TypeError: list indices must be integers or slices not tuple

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.

typeerror list indices must be integers or slices not tuple

# Forgetting to separate the elements of a list by a comma

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 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']]

All elements in a list must be separated by a comma.

# Using an incorrect index accessor

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]
We have to use an integer (e.g. 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']

# Accessing specific elements in a nested list

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.

# Getting a slice of a list

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.

# Accessing multiple not-consecutive list items

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'

# Converting a Python list to a numpy array

If 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 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

# Iterating over a list

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.

# Reassigning a variable to a tuple by mistake

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:

  • Using a pair of parentheses () creates an empty tuple
  • Using a trailing comma - a, or (a,)
  • Separating items with commas - a, b or (a, b)
  • Using the tuple() constructor

If 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2023 Borislav Hadzhiev