Typeerror float object is not iterable что за ошибка
Python TypeError: ‘float’ object not iterable Solution
Python can only iterate over an iterable object. This is a type of object that can return its members one at a time. If you try to iterate over a non-iterable object, like a floating-point number, you see an error that says “TypeError: ‘float’ object not iterable”.
- Career Karma matches you with top tech bootcamps Get exclusive scholarships and prep courses
- Career Karma matches you with top tech bootcamps Get exclusive scholarships and prep courses
In this guide, we talk about what this error means and why you may encounter it. We walk through an example to help you understand how to resolve this error in your code.
TypeError: ‘float’ object not iterable
Iterable objects include list, strings, tuples, and dictionaries. When you run a for loop on these data types, each value in the object is returned one by one.
Numbers, such as integers and floating points, are not iterable. There are no members in an integer or a floating-point that can be returned in a loop.
The result of the “TypeError: ‘float’ object not iterable” error is usually trying to use a number to tell a for loop how many times to execute instead of using a range() statement.
An Example Scenario
Here, we write a program that calculates the factors of a number. To start, we ask the user to insert a number whose factors they want to calculate:
The input() method returns a string. We cannot perform mathematical operations on a string. We’ve used the float() method to convert the value returned by input() to a floating-point number so that we can use it in a math operation.
Next, we write a for loop that calculates the factors of our number:
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 loop should go through every number until it reaches “factor”.
This loop uses the modulo operator to check whether there is a remainder left after dividing the factor by “n”, which is the number in an iteration of our loop. If there is a remainder, “n” is not a factor. If there is a remainder, our “if” statement executes and prints a message to the console.
Run our code and see what happens:
Our code returns a TypeError.
The Solution
In our example above, we’ve tried to iterate over “factor”, which is a float. We cannot iterate over a floating-point number in a for loop. Instead, we should iterate over a range of numbers between 1 and the number whose factor we want to calculate.
To fix our code, we need to use a range() statement. The range() statement generates a list of numbers in a specified range upon which a for loop can iterate. Let’s revise our for loop to use a range() statement:
Our range() statement generates a list of numbers between one and the value of “factor” plus one.
«float» object is not iterable
I am trying to find the mean of a list that contains the types int, float, and str. When I iterate through and print each item, the code works.
But then when I try to operate on each «i» it gives me the error «TypeError: ‘float’ object is not iterable». I am trying to iterate over each item, not each character.
Can anyone steer me in the right direction?
7 Answers 7
Means it goes through myList, or iterates through it.
and you did the += thing in the last line of the last snippet,
Floats aren’t iterable, as stated in the Traceback (aka error message)
Therefore, you have to append the i into the new list that you want. That’ll add it to the list.
So for that little snippet, you can do:
Your problem results from what happens when you try to add something to a list. Here is an example:
You can see that when you try to add something to a list, each individual «item» of whatever is on the right of the += operand is added separately to the list. This ability to separate an item into its components is called iteration, and when an object supports this we say the object is iterable.
The list object relies on this ability to iterate an object when trying to add things to a list.
Floats (and ints) are not iterable which is why you get the error. To fix the problem (as others have suggested), use the append() method, which just takes the item given in the argument and adds it as is to the list:
Преобразование float в str-ошибку: TypeError: объект «float» не является итерабельным
TypeError: ‘float’ object is not iterable
Отвечая на ваши вопросы в порядке:
Я пытаюсь суммировать, если несколько float, иначе сохраните его как float. Я просто пытаюсь понять, почему он не работает.
Для первой части, чтобы суммировать несколько поплавков или держать их как float, я бы попробовал что-то вроде этого:
Вторая часть, I am just trying to see why it not working. :
Ни одно из вышеперечисленных не будет работать, потому что вы не можете перебирать один номер, а float не является итерируемым. Примером итерабельности будет кортеж, список или, как выяснено, что такое итерируемый
Вы не можете повторять поплавок, вам нужно использовать только
Но если у вас иногда есть кортеж поплавков, вы можете проверить его раньше, используя isinstance()
Насколько я понял ваше требование, я думаю, это то, что вы хотите сделать:
Составьте список символов в номере с плавающей точкой и выполните суммирование всех символов, которые в нем являются цифрами.
Если да, то это поможет решить вашу проблему:
Возможно, вам придется протестировать ваш вход, чтобы узнать, является ли он tuple или нет:
Обновить:
Объяснение ваших ошибок:
Ошибка заключается в значении for x in ti части понимания, поскольку ti не является итерируемым.
Ошибка здесь в том, что sum ожидает итерабельности, и вы предоставили поплавок.
TypeError: ‘float’ object is not iterable
In this article, we will learn about the error “TypeError: ‘float’ object is not iterable”. This error occurs when we try to iterate through a float value which we know is not iterable.
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 a float value. But the float is not iterable. Float objects are not iterable because of the absence of the __iter__ method. Which we have discussed about in the below example 2.
Thus the error “TypeError: float object is not iterable” occurs.
Example 2:
Explanation:
In the above example, we are trying to print the list elements using the ‘for loop’. since the list is iterable, thus we can use the for loop for iteration.
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(3.4)
__iter__magicmethod is present.
__iter__ magic method is absent.
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 float is not an iterable object and a list is an iterable object.
‘float’ object is not iterable typerror
I’ve written a script that takes a large excel spreadsheet of data and strips away unwanted columns, rows that contain zero values in particular columns and then saves out to a csv. The piece that I’m stuck on is I’m also trying to remove rows that are missing cells. The way I was trying this was by way of:
But this isn’t working correctly as I’m getting the error:
File «/Users/kenmarold/PycharmProjects/sweetCrude/Work/sweetCrude.py»,
line 56, in PrepareRawData
if not all(map(len, each_row)) :
TypeError: ‘float’ object is not iterable
I’m not exactly sure how to resolve this, what’s the way forward on this? I’ve also attached the full script below.
3 Answers 3
This is a dirty patch.
EDIT: If the any/map/len raises it still, then I would try a different route to check if it’s empty.
Also I’m not sure why you are appending the entire row_list and not the current row. I changed it to appending each_row.
Your row_list contains a set of values, for example:
You then try to do this:
Python’s map function expects a list as the second argument, and tries to iterate over it to apply the function len to each item in the list. You can’t iterate a float.
I’m not entirely sure what you are trying to do here, but if you are wanting to check that none of the items in your row_list are None or an empty string, then you could do:
Your overall object appears to be to copy selected columns from all rows of one sheet of an Excel XLS file to a CSV file. Each output row must contain only valid cells, for some definition of «valid».
As you have seen, using map() is not a good idea; it’s only applicable if all the fields are text. You should apply tests depending generally on the datatype and specifically on the individual column.