Typeerror int object is not iterable python 3 как исправить
Перейти к содержимому

Typeerror int object is not iterable python 3 как исправить

TypeError: ‘int’ object is not iterable in Python

While programming in Python, it is a common practice to use loops such as for loops and while loops. These are used for iterating over lists and dictionaries for performing a variety of operations on the elements. But programmers often encounter an error called TypeError: ‘int’ object is not iterable.

This type of error occurs when the code is trying to iterate over a list of integer elements.

Let us understand it more with the help of an example.

Example 1

Explanation

In the above example, we are trying to iterate through a for loop using an integer value. But the integers are not iterable. As the Var variable holds a single integer value 5, it cannot be iterated using a for loop or any other loop.

This is because of the absence of __iter__ method. Which we have discussed about below in example 2.

Thus the error “TypeError: int object is not iterable” occurs.

Example 2

Output

Explanation

In the above example, we printing the elements of the list using the for loop. since the list is an iterable object, thus we can use the for loop to iterate through it. Thus, the TypeError is not encountered here. Dictionaries are also iterable in Python using the loops.

To know whether an object is iterable or not we can use the dir() method to check for the magic method __iter__ . If this magic method is present in the properties of specified objects then that item is said to be iterable

To check, do: dir(list) or dir(5)

Code

Output

__iter__ magic method is present.

Code

Output

On reviewing the output of the code. We notice that __iter__ magic method is absent. Thus, integers are not iterable.

Conclusion

The presence of the magic method __iter__ is what makes an object iterable. From the above article, we can conclude that. The __iter__ method is absent in the float object. Whereas it is present in the list object. Thus integer is not iterable object, unlike list.

Python typeerror: ‘int’ object is not iterable Solution

James Gallagher

What does this mean? How do I solve it? Those are the questions we’re going to answer in this article. We will discuss what the “‘int’ object is not iterable” error is, why it is raised, and how you can solve it.

The Problem: typeerror: ‘int’ object is not iterable

“typeerror: ‘int’ object is not iterable”

There are two parts to this error message: TypeError and the error message.

A TypeError is raised when a function is applied to an object of the wrong data type. For instance, if you try to apply a mathematical function to a string, or call a value like a function which is not a function, a TypeError is raised.

The error message tells us that you have tried to iterate over an object that is not iterable. Iterable objects are items whose values you can access using a “for loop”.

A Practice Scenario

One of the most common scenarios in which this error is raised is when you try to use a for loop with a number. This mistake is made because it’s easy to forget to use the range() function when you are using a for loop.

Consider the following code snippet:

81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.

Find Your Bootcamp Match

The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.

Start your career switch today

This code snippet uses one function. The count_occurance function counts how many times a number appears in the “values” list. This function iterates over all the values in “values” and keeps a running total of all those equal to a particular number. This number is specified as a parameter called “to_find”.

In our main program, we define a list called “values” with four values. We call our count_occurrence function to count how many threes are in our list of values. We then print out the response to the console.

Let’s run our code:

Oh no! An error has been raised. Now that we’ve replicated this error, we can solve it.

The Solution

Our error tells us that we’ve tried to iterate over an object that is not iterable. If we look at the error message in detail, we can see it points us to the line where the problem occurs:

The problem with this line is that we are trying to iterate over a number.

len(values) is equal to 4. That’s how many values are in the list “values”. If we try to iterate over a number, nothing happens. This is because for loops only work with iterable objects.

  • Career Karma matches you with top tech bootcamps
  • Get exclusive scholarships and prep courses

To solve this problem, we need to make sure our for loop iterates over an iterable object. We can add a range() statement to our code to do this:

This statement will create an iterable object with a list of values in the range of 0 and the number of items in the “values” list.

Let’s try to run our code again with the range() statement. Our code returns:

Our code has successfully found all the instances of 3 in the list. Our code has counted them all up and then printed the total number of times 3 appears in the list to the console.

Int Object is Not Iterable – Python Error [Solved]

Kolade Chris

Kolade Chris

Int Object is Not Iterable – Python Error [Solved]

If you are running your Python code and you see the error “TypeError: ‘int’ object is not iterable”, it means you are trying to loop through an integer or other data type that loops cannot work on.

In Python, iterable data are lists, tuples, sets, dictionaries, and so on.

In addition, this error being a “TypeError” means you’re trying to perform an operation on an inappropriate data type. For example, adding a string with an integer.

Today is the last day you should get this error while running your Python code. Because in this article, I will not just show you how to fix it, I will also show you how to check for the __iter__ magic methods so you can see if an object is iterable.

How to Fix Int Object is Not Iterable

If you are trying to loop through an integer, you will get this error:

One way to fix it is to pass the variable into the range() function.

In Python, the range function checks the variable passed into it and returns a series of numbers starting from 0 and stopping right before the specified number.

The loop will now run:

Another example that uses this solution is in the snippet below:

How to Check if Data or an Object is Iterable

To check if some particular data are iterable, you can use the dir() method. If you can see the magic method __iter__ , then the data are iterable. If not, then the data are not iterable and you shouldn’t bother looping through them.

The __iter__ magic method is not found in the output, so the variable perfectNum is not iterable.

The magic method __iter__ was found, so the list jerseyNums is iterable.

Conclusion

In this article, you learned about the “Int Object is Not Iterable” error and how to fix it.

You were also able to see that it is possible to check whether an object or some data are iterable or not.

If you check for the __iter__ magic method in some data and you don’t find it, it’s better to not attempt to loop through the data at all since they’re not iterable.

Thank you for reading.

Kolade Chris

Kolade Chris

Web developer and technical writer focusing on frontend technologies.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *