How to Solve Python TypeError: list indices must be integers, not tuple

by | Programming, Python, Tips

In Python, we index lists with numbers. To access an item from a list, you must refer to its index position using square brackets []. Using a tuple instead of a number as a list index value will raise the error “TypeError: list indices must be integers, not tuple”.

This tutorial will go through the error and an example scenario to learn how to solve it.


TypeError: list indices must be integers, not tuple 

What is a TypeError?


TypeError
 tells us that we are trying to perform an illegal operation on a Python data object.

Indexing a List

Indexing a list starts from the value 0 and increments by 1 for each subsequent element in the list. Let’s consider a list of pizzas:

pizza_list = ["margherita", "pepperoni", "four cheeses", "ham and pineapple"]

The list has four values. The string “margherita” has an index value of 0, and “pepperoni” has 1. To access items from the list, we need to reference these index values.

print(pizza_list[2])
four cheeses

Our code returns “four cheeses“.

In Python, TypeError occurs when we do an illegal operation for a specific data type.

Tuples are ordered, indexed collections of data. We cannot use a tuple value to access an item from a list because tuples do not correspond to any index value in a list.

You may encounter a similar TypeError to this one called TypeError: list indices must be integers or slices, not str, which occurs when you try to access a list using a string.

The most common sources of this error are defining a list of lists without comma separators and using a comma instead of a colon when slicing a list.

Example #1: List of Lists with no Comma Separator

Let’s explore the error further by writing a program that stores multiples of integers. We will start by defining a list of which stores lists of multiples for the numbers two and three.

multiples = [

    [2, 4, 6, 8, 10]

    [3, 6, 9, 12, 15]

]

We can ask a user to add the first five of multiples of the number four using the input() function:

first = int(input("Enter first multiple of 4"))

second = int(input("Enter second multiple of 4"))

third = int(input("Enter third multiple of 4"))

fourth = int(input("Enter fourth multiple of 4"))

fifth = int(input("Enter fifth multiple of 4"))

Once we have the data from the user, we can append this to our list of multiples by enclosing the values in square brackets and using the append() method.

multiples.append([first, second, third, fourth, fifth])

print(multiples)

If we run this code, we will get the error.”

TypeError                                 Traceback (most recent call last)
      1 multiples = [
      2 [2, 4, 6, 8, 10]
      3 [3, 6, 9, 12, 15]
      4 ]

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

The error occurs because there are no commas between the values in the multiples list. Without commas, Python interprets the second list as the index value for the first list, or:

# List           Index

[2, 4, 6, 8, 10][3, 6, 9, 12, 15]

The second list cannot be an index value for the first list because index values can only be integers. Python interprets the second list as a tuple with multiple comma-separated values.

Solution

To solve this problem, we must separate the lists in our multiples list using a comma:

multiples = [

[2, 4, 6, 8, 10],

[3, 6, 9, 12, 15]

]

first = int(input("Enter first multiple of 4:"))

second = int(input("Enter second multiple of 4:"))

third = int(input("Enter third multiple of 4:"))

fourth = int(input("Enter fourth multiple of 4:"))

fifth = int(input("Enter fifth multiple of 4:"))
multiples.append([first, second, third, fourth, fifth])

print(multiples)

If we run the above code, we will get the following output:

Enter first multiple of 4:4

Enter second multiple of 4:8

Enter third multiple of 4:12

Enter fourth multiple of 4:16

Enter fifth multiple of 4:20

[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]

The code runs successfully. First, the user inputs the first five multiples of four, the program stores that information in a list and appends it to the existing list of multiples. Finally, the code prints out the list of multiples with the new record at the end of the list.

Example #2: Not Using a Colon When Slicing a List

Let’s consider the list of multiples from the previous example. We can use indexing to get the first list in the multiples list.

first_set_of_multiples = multiples[0]

print(first_set_of_multiples)

Running this code will give us the first five multiples of the number two.

[2, 4, 6, 8, 10]

Let’s try to get the first three multiples of two from this list:

print(first_set_of_multiples[0,3])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
1 print(first_set_of_multiples[0,3])

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

The code fails because we pass [0,3] as the index value. Python only accepts integers as indices for lists.

Solution

To solve this problem and access multiple elements from a list, we need to use the correct syntax for slicing. We must use a colon instead of a comma to specify the index values we select.

print(first_set_of_multiples[0:3])
[2, 4, 6]

The code runs successfully, and we get the first three multiples of the number two printed to the console.

Note that when slicing, the last element we access has an index value one less than the index to the right of the colon. We specify 3, and the slice takes elements from 0 to 2. To learn more about slicing, go to the article titled “How to Get a Substring From a String in Python“.

Summary

Congratulations on reading to the end of this tutorial. The Python error “TypeError: list indices must be integers, not tuple” occurs when you specify a tuple value as an index value for a list. This error commonly happens if you define a list of lists without using commas to separate the lists or use a comma instead of a colon when taking a slice from a list. To solve this error, make sure that when you define a list of lists, you separate the lists with commas, and when slicing, ensure you use a colon between the start and end index.

For further reading on the list and tuple data types, go to the article: What is the Difference Between List and Tuple in Python?

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee