Why does the error mention tuples?
Others have explained that the problem was the missing ,
, but the final mystery is why does the error message talk about tuples?
As mentioned by 6502 the code:
coin_args = [
["pennies", '2.5', '50.0', '.01']
["nickles", '5.0', '40.0', '.05']
]
has the exact same problem as:
coin_args = [
["pennies", '2.5', '50.0', '.01']["nickles", '5.0', '40.0', '.05']
]
which has the same problem as:
mylist = ["pennies", '2.5', '50.0', '.01']
coin_args = [
mylist["nickles", '5.0', '40.0', '.05']
]
which has the same problem as:
mylist = [1, 2]
print(mylist[3, 4])
When you do mylist[0]
, that calls __getitem__
, which deals with []
resolution.
But Python syntax also allows you to pass two arguments in general, e.g.: object[1, 2]
. When that happens, __getitem__
receives a tuple:
class C(object):
def __getitem__(self, k):
return k
# Single argument is passed directly.
assert C()[0] == 0
# Multiple indices generate a tuple.
assert C()[0, 1] == (0, 1)
The problem is that the __getitem__
for the list
built-in class cannot deal with tuple arguments like that, only integers, and so in complains:
TypeError: list indices must be integers, not tuple
You could however implement __getitem__
in your own classes such that myobject[1, 2]
does something sensible.
More examples of __getitem__
action at: https://stackoverflow.com/a/33086813/895245
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']
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!
A list is a data structure in Python that stores elements of different data types sequentially. We can access each element using its index number. The
list
provides a unique sequential integer value to every element called the index number, which starts from 0 and ends at n-1 (n is the total number of elements present in the list).
When we wish to access any list elements, we use its 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 receive the
TypeError: list indices must be integers or slices, not tuple
Error.
In this tutorial, we will learn what
TypeError: list indices must be integers or slices, not tuple
error is and how to solve it. We will also look at a common scenario example and a corresponding solution example.
The Python error
TypeError: list indices must be integers, not tuple
is divided into two statements Error Type and Error Message.
-
Error Type (
TypeError
): TypeError occurs in Python when we incorrectly operate a Python object type. -
Error Message (
list indices must be integers or slices, not tuple
): This error message tells 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 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 values 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 receive the error in the above program because, at line 4, we passed a tuple as an index value to access the first element of
my_list
.
The Python interpreter read the comma-separated values as a tuple. That’s why in line 4, where we printed 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
, which 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 slicing would be a perfect choice for that list. We can access a sequential part of the list using a single statement using list slicing.
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 three 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 to 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 arises 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
When you’re working in Python, especially with lists and tuples, you might come across this error:
TypeError: list indices must be integers or slices, not tuple
This error is caused by the fact that you’re trying to access a list element by a tuple.
In this post, we’ll look and some example code that causes this error and how to fix it.
How to fix TypeError: list indices must be integers or slices, not tuple
Before we learn how to fix it, let’s look at some example code that causes this error:
locations = [
["New York", "USA"]
["Paris", "France"]
]
london = ["London", "UK"]
locations.append(london)
print(locations)
Depending on your compiler, you might even already get the solution to this problem:
<string>:2: SyntaxWarning: list indices must be integers or slices, not tuple; perhaps you missed a comma?
Traceback (most recent call last):
File "<string>", line 2, in <module>
TypeError: list indices must be integers or slices, not tuple
It says it on the first line of this error, that perhaps you missed a comma, and indeed we did.
By defining locations
without a comma, we’re creating a list of lists, instead of a list of tuples.
That distinction is the root of the problem.
All we need to do is add a comma so that the compiler understands that this is a list of tuples:
locations = [
["New York", "USA"],
["Paris", "France"]
]
london = ["London", "UK"]
locations.append(london)
print(locations)
As expected, this now works without errors.
[['New York', 'USA'], ['Paris', 'France'], ['London', 'UK']]
Conclusion
In this post, we learned how to fix the problem of TypeError: list indices must be integers or slices, not tuple.
Simply ensure that you are using a list of tuples, instead of a list of lists, which can be done by adding a comma to separate the different tuples.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
-
Support Us
-
Join
-
Share
-
Tweet
-
Share
Give feedback on this page!