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

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.

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

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:\Projects\Tryouts\main.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:\Projects\Tryouts\main.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:\Projects\Tryouts\main.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']

0 Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like
XOR in Python

XOR in Python

XOR Operator in Python is also known as “exclusive or”  that compares two binary numbers bitwise if two bits are…