TypeError: 'list' object cannot be interpreted as an integer

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: 'list' object cannot be interpreted as an integer #

The Python "TypeError: 'list' object cannot be interpreted as an integer" occurs when we pass a list to a function that expects an integer argument, e.g. range(). To solve the error, either pass the length of the list, e.g. len(my_list) or pass an integer to the function.

typeerror list object cannot be interpreted as an integer

Here is an example of how the error occurs.

main.py
my_list = ['a', 'b', 'c'] # 👇️ expects to get called with integer but is called with list # ⛔️ TypeError: 'list' object cannot be interpreted as an integer for i in range(my_list): print(i)
The range function expects an integer as an argument, however, we pass it a list which causes the error.

To solve the error, we have to pass an integer instead of a list to the function.

For example, you can pass it the length of the list if that's what you intended to do.

main.py
my_list = ['a', 'b', 'c'] for i in range(len(my_list)): print(i) # 👉️ 0, 1, 2

If you meant to iterate over the list, remove the call to range().

main.py
my_list = ['a', 'b', 'c'] # ✅ iterate over list for item in my_list: print(item) # 👉️ 'a', 'b', 'c' # ✅ iterate over list with index for idx, item in enumerate(my_list): print(idx, item) # 👉️ 0 a, 1 b, 2 c

If you need the index when iterating over a list, use the enumerate() function.

The reason we got the error is because the range function takes integers as arguments, but we passed a list to the function.

The range function is commonly used for looping a specific number of times in for loops and takes the following parameters:

NameDescription
startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)

If you only pass a single argument to the range() constructor, it is considered to be the value for the stop parameter.

If you are getting the error with a different function, you either have to pass the length of the list len(my_list) as an argument to the function or figure out where the variable gets assigned a list in your code.

Make sure you aren't declaring a variable that stores an integer initially and overriding it somewhere in your code.

main.py
my_int = 10 # 👇️ reassigned variable to a list by mistake my_int = ['a', 'b', 'c'] # 👇️ function expects to be called with an integer argument # ⛔️ TypeError: 'list' object cannot be interpreted as an integer result = range(my_int)

We initially set the my_int variable to an integer but later reassigned it to a list which caused the error.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.