Typeerror list indices must be integers or slices not tuple как исправить

TypeError: list indices must be integers or slices, not tuple occurs when you access specify tuple to access the list or if you have missed comma in list of lists

If you are accessing the list elements in Python, you need to access it using its index position. If you specify a tuple or a list as an index, Python will throw typeerror: list indices must be integers or slices, not tuple.

This article will look at what this error means and how to resolve the typeerror in your code.

Example 1 – 

Let’s consider the below example to reproduce the error.

# Python Accessing List
numbers=[1,2,3,4]
print(numbers[0,3])

Output

Traceback (most recent call last):
  File "c:ProjectsTryoutsmain.py", line 3, in <module>
    print(numbers[0,3])
TypeError: list indices must be integers or slices, not tuple

In the above example, we are passing the [0,3] as the index value to access the list element. Python interpreter will get confused with the comma in between as it treats as a tuple and throws typeerror: list indices must be integers or slices, not tuple.

Solution 

We cannot specify a tuple value to access the item from a list because the tuple doesn’t correspond to an index value in the list. To access a list, you need to use a proper index, and instead of comma use colon : as shown below.

# Python Accessing List
numbers=[1,2,3,4]
print(numbers[0:3])

Output

[1, 2, 3]

Example 2 – 

Another common issue which developers make is while creating the list inside a list. If you look at the above code, there is no comma between the expressions for the items in the outer list, and the Python interpreter throws a TypeError here.

coin_args = [
  ["pennies", '2.5', '50.0', '.01']
  ["nickles", '5.0', '40.0', '.05']
]

print(coin_args[1])

Output

c:ProjectsTryoutsmain.py:2: SyntaxWarning: list indices must be integers or slices, not tuple; perhaps you missed a comma?
  ["pennies", '2.5', '50.0', '.01'] 
Traceback (most recent call last):
  File "c:ProjectsTryoutsmain.py", line 2, in <module>
    ["pennies", '2.5', '50.0', '.01']
TypeError: list indices must be integers or slices, not tuple

Solution

The problem again is that we have forgotten to add the comma between our list elements. To solve this problem, we must separate the lists in our list of lists using a comma, as shown below.

coin_args = [
  ["pennies", '2.5', '50.0', '.01'] ,
  ["nickles", '5.0', '40.0', '.05']
]

print(coin_args[1])

Output

['nickles', '5.0', '40.0', '.05']

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

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?
    • Indexing a List
  • Example #1: List of Lists with no Comma Separator
    • Solution
  • Example #2: Not Using a Colon When Slicing a List
    • Solution
  • Summary

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!

Python Lists

use indexing to store its element in sequential order. In indexing, the list provides a unique sequential integer value to every element, and the index number starts from 0 up to n-1, where n is the total number of elements present in the list.

To access the individual element from a list, we can use the element index number inside the square bracket preceded by the list name. But if we specify a tuple object instead of an index value to access a list element, we will receive the

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

Error.

In this Python debugging tutorial, we will learn what is

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

Error in Python and how to solve it. We will also have a look at a common scenario example where most Python learners commit this mistake.

The Python error

TypeError: list indices must be integers, not tuple

is divided into two statements Error Type and Error Message.

  1. Error Type (


    TypeError


    ): TypeError occurs in Python when we perform an incorrect operation of a Python object type.
  2. Error Message (


    list indices must be integers or slices, not tuple


    ): This error message is telling us that we are using a tuple object instead of a valid index value.


Error Reason

The reason for this error is quite obvious, if you look at the error message, you can clearly tell why this error occurred in your program. Python list index value is always an integer value, even in list slicing, we use index integer value separated with colons.

But if we pass a tuple or values separated by commas as an index value, we will receive the

list indices must be integers or slices, not tuple

Error.


Example

my_list =['a', 'b', 'c', 'd', 'e', 'f']

# access list first element
print(my_list[0,])


Output

Traceback (most recent call last):
File "main.py", line 4, in <module>
print(my_list[0,])
TypeError: list indices must be integers or slices, not tuple


Break the code

We are receiving the error in our above program because at line 4, we have passed a tuple as an index value to access the first element of

my_list

object.

The Python interpreter read the comma-separated values as a tuple. That’s why in line 4, where we are printing the

my_list

first, the element using the index value

0,

.

Python treated the

0,

statement as a tuple and threw the error because the index value must be an integer, not a tuple.


Solution

To solve the above program, we just need to remove the comma after

0

and it will be treated as an integer object.

my_list =['a', 'b', 'c', 'd', 'e', 'f']

# access list first element
print(my_list[0])


Output

a


A Common Scenario

The most common scenario where many Python learners encounter this error is when they use commas

,

by mistake for list slicing instead of a colon

:

.


Example

Let’s say we want to access the first four elements from our list, and for that list, slicing would be a perfect choice. Using list slicing, we can access a sequential part of the list using a single statement.

my_list =['a', 'b', 'c', 'd', 'e', 'f']

# access first 3 elements
print(my_list[0,4])


Output

Traceback (most recent call last):
File "main.py", line 4, in <module>
print(my_list[0,4])
TypeError: list indices must be integers or slices, not tuple


Break the code

In the above example, we tried to perform Python list slicing on our list object

my_list

to access its first 3 elements. But in line 4, instead of a colon

:

we used commas to specify the start

0

and end

4

indices for the list slicing.

Python interpreter read the

1,4

statement as a tuple and return the TypeError


list indices must be integers or slices, not tuple


.


Solution

The solution for the above problem is very simple. All we need to do is follow the correct Python list slicing syntax that is as follows:

list_name[start_index : end_index : steps]


Example

my_list =['a', 'b', 'c', 'd', 'e', 'f']

# access first 3 elements
print(my_list[0:4])


Output

['a', 'b', 'c', 'd']


Final Thoughts!

In this Python tutorial, we learned about

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

Error and how to solve it. This error raises in Python when we use a tuple object instead of the integer index value to access an element from a Python list.

To solve this problem, you need to make sure that the error list element you are using must be accessed through a proper index value, not a tuple.

If you are still getting this error in your python program, you can share your code in the comment section with the query, and we will help you to debug it.


People are also reading:

  • Online Python Compiler

  • Python ValueError: invalid literal for int() with base 10: Solution

  • Python XML Parser Tutorial

  • Python TypeError: ‘float’ object is not callable Solution

  • np.arange() | NumPy Arange Function in Python

  • Python indexerror: list assignment index out of range Solution

  • Python Internet Access

  • Python typeerror: ‘list’ object is not callable Solution

  • Python String count()

  • Python TypeError: can only concatenate str (not “int”) to str Solution

Are you looking for a way to fix “TypeError: list indices must be integers or slices not tuple” error?

Python TypeError is the exception that indicates the invalid usage of an object type in an operation. The error usually occurs if an operation is performed on an object that does not support the operation itself, or an object of incorrect type. For example, TypeError is raised every time you try to concatenate an integer with a string.

In this article, we will dig deep into the “TypeError: list indices must be integers or slices not tuple” error and how beginners can debug and fix it quickly and effectively.

“TypeError: list indices must be integers or slices not tuple” indicates that you’re accessing a Python list using a tuple instead of an index or an index range. The “list indices” in the error message simply means “list indexes”.

Python beginners often mixed the slice syntax (using colons) with the list syntax (using commas).

Another common thing that cause this type of error is accessing a non-nested list using multi-dimensional slicing.

In order to fix the error, make sure you’re using the right syntax with the right object. Let’s see some examples:

# TypeError: list indices must be integers or slices, not tuple # because of missing comma a_list = [['a', 'b', 'c']['a1', 'b1', 'c1']]

Code language: Python (python)

In the example above, we forgot to add a comma when we’re trying to define a nested list, so Python mistakenly recognize it as we’re trying to access a list using indexes, hence display a TypeError.

Find the tuple indexes

There is a chance you may have used a tuple to access a list in a straightforward way, which triggers “TypeError: list indices must be integers or slices not tuple” error. Typically, such source code may look like below (oversimplified example).

a_list = ['a', 'b', 'c', 'd', 'e'] indexes = 0, 1 result = my_list[my_tuple]

Code language: Python (python)

In real life, the indexes may be the result of another operation, or the result from a function. In Python, typically a tuple is created by wrapping several objects in a parentheses pair (). For example: ('a', 'b') or ('a', 'b', 'c', 'd'). The parentheses are optional, which means 'a', 'b', 'c', 'd' also creates a tuple as well. In addition to that, you can also create a tuple using one of the following ways :

  • A pair of parentheses () creates an empty tuple
  • 0, or ('a',) also creates a tuple
  • Explicitly using tuple() constructor. For example, `tuple(‘a’, ‘b’).

With that many ways to create a tuple, follow the suggestions below to debug your program:

  • Use the type class to inspect the type of each object.
  • Alternatively, use isinstance to check whether the in object is an instance or a subclass of a class or not.

Check your syntax

In this case, simply inspect and add commas to the list definition accordingly.

# a_list definition with the proper syntax a_list = [['a', 'b', 'c'],['a1', 'b1', 'c1']]

Code language: Python (python)

Another common scenario is using an incorrect index accessor.

a_list = [['a', 'b', 'c'],['a1', 'b1', 'c1']] result = a_list[0, 0] # Will cause TypeError: list indices must be integers or slices, not tuple

Code language: Python (python)

In the example, we two integer separated by a comma to get an element from a nested list. This is the wrong syntax, which causes Python interpreter to mistakenly recognize it as a tuple.

If you’re trying to access an element from a nested list, you would have to use two pair of square brackets to do it. The first bracket pair will return the first element, then the second one will be the index to the element you just got.

a_list = [['a', 'b', 'c'],['a1', 'b1', 'c1']] result = a_list[0][0] # "result" will be 'a' # This equals to result1 = a_list[0] # Returns ['a', 'b', 'c'] result2 = result1[0] # Returns 'a'

Code language: Python (python)

In case you want to get a part of the list in Python, use the slicing syntax as follows:

a_list = ['a', 'b', 'c', 'd', 'e', 'f'] print(a_list[0:3]) # returns ['a', 'b', 'c'] print(a_list[:3]) # returns ['a', 'b', 'c'] print(a_list[3:]) # returns ['d', 'e', 'f']

Code language: Python (python)

Here we use the colon to separate the start and end indexes. Both the start and end index are optional. If not specified, the value for start index would be 0 and end index would be defaulted to the length of the list.

How to access multiple, unrelated list items without slicing? Simple, just use an index to access them separately and concatenate them afterwards.

a_list = ['a', 'b', 'c', 'd', 'e', 'f'] print([a_list[0], a_list[2], a_list[4]]) # returns ['a', 'c', 'e']

Code language: Python (python)

The code doesn’t look very elegant, but it does the job without having to use an external library. Another way to do it is using a for loop like below :

a_list = ['a', 'b', 'c', 'd', 'e', 'f'] indexes = [0,2,4] result = [a_list[x] for x in indexes] print(result) # returns ['a', 'c', 'e']

Code language: Python (python)

We hope that the article helped you successfully debug and fix “TypeError: list indices must be integers or slices not tuple” error in Python, as well as avoid encountering it in the future. We’ve also written a few other guides for fixing common Python errors, such as Fix “Max retries exceeded with URL” ,Python Unresolved Import in VSCode or “IndexError: List Index Out of Range” in Python.
If you have any suggestion, please feel free to leave a comment below.

Estimated reading time: 3 minutes

When working with Python lists in your data analytics projects, when you trying to read the data, a common problem occurs if you have a list of lists, and it is not properly formatted.

In this instance, Python will not be able to read one or more lists and as a result, will throw this error.

In order to understand how this problem occurs, we need to understand how to create a list of lists.

How to create a lists of lists

Let’s look at a simple list:

a = [1,2,3]
print(a)
print(type(a))

Result:
[1, 2, 3]
<class 'list'>

Let’s create a second list called b:

b = [4,5,6]
print(b)
print(type(b))

Result:
[4, 5, 6]
<class 'list'>

So if we want to join the lists together into one list ( hence a list of lists) then:

a = [1,2,3]
b = [4,5,6]

list_of_lists = []
list_of_lists.append(a)
list_of_lists.append(b)
print(list_of_lists)
print(type(list_of_lists))

Result:
[[1, 2, 3], [4, 5, 6]]
<class 'list'>

So as can be seen the two lists are contained within a master list called “list_of_lists”.

So why does the error list indices must be integers or slices, not tuple occur?

Reason 1 ( Missing commas between lists)

If you manually type them in and forget the comma between the lists this will cause your problem:

a=[[1,2,3][4,5,6]]
print(a)

Result (Error):
Traceback (most recent call last):
  line 10, in <module>
    a=[[1,2,3][4,5,6]]
TypeError: list indices must be integers or slices, not tuple

But if you put a comma between the two lists then it returns no error:

a=[[1,2,3],[4,5,6]]
print(a)

Result (no error):
[[1, 2, 3], [4, 5, 6]]
Process finished with exit code 0

Reason 2 ( Comma in the wrong place)

Sometimes you have a list, and you only want to bring back some elements of the list, but not others:

In the below, we are trying to bring back the first two elements of the list.

a= [1,2,3,4,5]
print(a[0:,2])

Result:
Traceback (most recent call last):
   line 14, in <module>
    print(a[0:,2])
TypeError: list indices must be integers or slices, not tuple

The reason that the same error happens is the additional comma in a[0:,2], causes the error to appear as Python does not know how to process it.

This is easily fixed by removing the additional comma as follows:

a= [1,2,3,4,5]
print(a[0:2])

Result:
[1, 2]
Process finished with exit code 0

So why is there a mention of tuples in the error output?

The final piece of the jigsaw needs to understand why there is a reference to a tuple in the error output?

If we return to a looking at a list of lists and look at their index values:

a=[[1,2,3],[4,5,6]]
z = [index for index, value in enumerate(a)]
print(z)

Result:
[0, 1]
Process finished with exit code 0

As can be seen, the index values are 0,1, which is correct.

As before removing the comma gives the error we are trying to solve for:

a=[[1,2,3][4,5,6]]
z = [index for index, value in enumerate(a)]
print(z)

Result:
Traceback (most recent call last):
  line 16, in <module>
    a=[[1,2,3][4,5,6]]
TypeError: list indices must be integers or slices, not tuple

BUT the reference to the tuple comes from the fact that when you pass two arguments (say an index value) a Tuple is created, but in this instance, as the comma is missing the tuple is not created and the error is called.

This stems from the __getitem__ for a list built-in class cannot deal with tuple arguments that are not integers ( i.e. 0,1 like we have returned here) , so the error is thrown, it is looking for the two index values to pass into a tuple.

Понравилась статья? Поделить с друзьями:
  • Typeerror int object is not iterable python как исправить
  • Typeerror int object is not callable python как исправить
  • Typeerror float object is not callable как исправить
  • Typeerror error 1034 type coercion failed cannot convert
  • Typeerror error 1010 a term is undefined and has no properties