Python typeerror tuple indices must be integers

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

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.

Table of contents

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.

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.

Читайте также:  Как выучить программирования java

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.

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

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

Читайте также:  Javascript prototype call this

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!

Share this:

Источник

Python typeerror tuple indices must be integers

Last updated: Feb 2, 2023
Reading time · 4 min

banner

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

Copied!
# ⛔️ 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.

Copied!
# ✅ works my_list = [['a', 'b'], ['c', 'd']] print(my_list)

add comma between elements of list

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.

Copied!
my_list = [['a', 'b'], ['c', 'd']] # ⛔️ TypeError: list indices must be integers or slices, not tuple result = my_list[0, 0]
Copied!
my_list = ['a', 'b', 'c', 'd'] print(my_list[2]) # 👉️ 'c' print(my_list[1:3]) # 👉️ ['b', 'c']

using integer or slice index accessor

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

Copied!
my_list = [['a', 'b'], ['c', 'd']] print(my_list[0][0]) # 👉️ 'a' print(my_list[0][1]) # 👉️ 'b'

accessing specific elements in nested list

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.

Copied!
my_list = ['a', 'b', 'c', 'd', 'e'] print(my_list[0:3]) # 👉️ ['a', 'b', 'c'] print(my_list[3:]) # 👉️ ['d', 'e']

getting slice of list

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

Читайте также:  Update xml files java

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

Copied!
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.

Copied!
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.

Copied!
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.

Copied!
pip install numpy # 👇️ or pip3 pip3 install numpy

# Iterating over a list

If you need to iterate over a list, use a for loop.

Copied!
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.

Copied!
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.

Copied!
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.

Copied!
my_list = ['a', 'b', 'c', 'd', 'e'] print(type(my_list)) # 👉️ print(isinstance(my_list, list)) # 👉️ True my_tuple = 0, 1 print(type(my_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.

Источник

Оцените статью