Many built-in functions, like range(), expect integer values as an input. If you try to use a list as an input to a function that expects an integer, you’ll encounter the “TypeError: ‘list’ object cannot be interpreted as an integer” error.
This guide discusses what this error means and why you may encounter it. We’ll walk through an example of this error so you can figure out how it works and how to solve it.
TypeError: ‘list’ object cannot be interpreted as an integer
This error occurs when you pass a list value through a function that expects an integer. The most common instance of this error is when you specify a list in a range() function.
The range() function creates a list of whole numbers in a particular range. Consider the following example:
This code creates a range() object. This object contains values between 0 and 3. When our code runs, it prints out each one of these values to the console:
Read more: Harry styles dressed as a granny
The range() function can only accept integers because it needs to know the start and end point for the range of numbers to create. The function cannot create a range of values from a list object.
An Example Scenario
Build a program that prints to the console whether goods at an electronics store are on sale. To start, define two lists with the data that we will use:
The first list contains a list of the products sold at the store. The second list contains whether each product is on sale.
Next, use a for loop to print to the console telling us the name of each product and whether it is on sale:
Our loop goes through the list of products.
Read more: Rocket league unblocked 911
If the corresponding value in “on_sale” is equal to True, a message is printed to the console telling us the product is on sale. Otherwise, a message telling us the product is not on sale is displayed on the console. These conditions are evaluated using an if…else statement.
Let’s run our program to see if it works:
There is an error in our program.
According to our error message, the line of code that is causing the error is where we define our range() statement.
This error is caused because we are trying to create a range using a list. The range() method can only create a range of numbers between integer values.
Read more: Aztec pottery designs
To solve this error, use the len() method to calculate the length of the “products” array. We can use this value in our for loop:
Let’s run our code and see what happens:
Our program successfully prints out four messages. Each message represents a unique product sold at the electronics store and informs us of whether that product is on sale.
The “TypeError: ‘list’ object cannot be interpreted as an integer” error is raised when you pass a list as a value in a function that expects an integer as an input. To solve this error, make sure you only pass an integer through the function that has raised the error.
Now you have the knowledge you need to fix this error like a professional coder!