How to Fix TypeError: list indices must be integers or slices, not tuple in Python
When you're working in Python, especially with lists and tuples, you might come across this error:
BASHTypeError: 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:
PYTHONlocations = [
["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:
BASH<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:
PYTHONlocations = [
["New York", "USA"],
["Paris", "France"]
]
london = ["London", "UK"]
locations.append(london)
print(locations)
As expected, this now works without errors.
BASH[['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!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Getting Started with Express
- Create an RSS Reader in Node
- How to Set Up Cron Jobs in Linux
- How to deploy a PHP app using Docker
- Getting Started with Deno
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Getting Started with React