Float object is not iterable python ошибка

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.

mylist = ["hello", 89.21, -3, "goodbye", 21, 0.0056, -12.34, "thank you", "please", 999.44409]
newlist = []
for i in mylist:
    print(i)

and the result is

hello
89.21
-3
goodbye
21
0.0056
-12.34
thank you
please
999.44409

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.

    for i in mylist:
    if type(i)== int or type(i)== float:
        newlist += i

Can anyone steer me in the right direction?

Bill Lynch's user avatar

Bill Lynch

79.6k16 gold badges127 silver badges172 bronze badges

asked Apr 7, 2015 at 4:50

Elizabeth Bernabe's user avatar

Try this:

for i in mylist: 
  if type(i)== int or type(i)== float:
    newlist.append(i) 

answered Apr 7, 2015 at 4:55

Esparta Palma's user avatar

the line

for i in myList

Means it goes through myList, or iterates through it.

example. if your string was "hello",

and you did the += thing in the last line of the last snippet,

The newList would become ['h','e','l','l','o'], which is not desired.

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:

for i in mylist: 
    if type(i)== int or type(i)== float:
        newlist.append(i) 

answered Apr 7, 2015 at 4:57

Your problem results from what happens when you try to add something to a list. Here is an example:

>>> i = []
>>> i += 'hello'
>>> i
['h', 'e', 'l', 'l', 'o']

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:

>>> i.append('hello')
>>> i
['h', 'e', 'l', 'l', 'o', 'hello']
>>> i.append(10)
>>> i
['h', 'e', 'l', 'l', 'o', 'hello', 10]

answered Apr 7, 2015 at 4:58

Burhan Khalid's user avatar

Burhan KhalidBurhan Khalid

169k18 gold badges243 silver badges282 bronze badges

Replace this:

newlist += i

with:

newlist += [i]     

demo:

>>> [3.0] +4.0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "float") to list

>>> [3.0] + [4.0]
[3.0, 4.0]

you can also you list.append to append elements at the end of list

newlist.append(i)

answered Apr 7, 2015 at 4:55

Hackaholic's user avatar

HackaholicHackaholic

18.9k4 gold badges54 silver badges71 bronze badges

newlist is a list here, Actually you are adding list reference with the value.

Instead of that, try this

newlist.append(i) 

answered Apr 7, 2015 at 5:05

Selva Mathan's user avatar

Ideally if you are looking to check if the type is a number such as int or float while iterating then you’ll want to use isinstance, doing something such as:

import numbers

mylist = ["hello", 89.21, -3, "goodbye", 21, 0.0056, -12.34, "thank you", "please", 999.44409]
newlist = []
for i in mylist:
    if isinstance(i, (int, float)):
        newlist += [i]
print(newlist)

Output:

[89.21, -3, 21, 0.0056, -12.34, 999.44409]

answered Apr 7, 2015 at 5:16

l'L'l's user avatar

l’L’ll’L’l

44.5k10 gold badges94 silver badges145 bronze badges

When you try to do a newlist += i, python complains because this operation is valid only if i itself was a list like newlist or any other iterable like a tuple. Then this operation would have combined the results and stored the result in newlist.

To add i to the newlist, you should use newlist.append(i) instead.

jesterjunk's user avatar

answered Apr 7, 2015 at 4:59

Saksham Varma's user avatar

0

Floats and iterables are distinct objects In Python. A float is any decimal point number, and an iterable is an object capable of returning elements one at a time, for example, a list. A float is a single value and does not contain other values. If you try to iterate over a float, you will raise the error “TypeError: ‘float’ object is not iterable“.

To solve this error, ensure you use the range() method, for example,

for number in range(floating_point_number)

to iterate over a range of numbers up to the specified floating_point_number.

This tutorial will go through the error in detail. We will go through two example scenarios and learn how to solve them.


Table of contents

  • TypeError: ‘float’ object not iterable
    • What is a TypeError?
    • Difference Between a Float and an Iterable
  • Example #1: Iterate Over a Floating Point Number
    • Solution #1: Convert float to string Using the str() Method
    • Solution #2: Iterate Using the range() Method
  • Example #2: Determine if a Number is Prime
    • Solution
  • Summary

TypeError: ‘float’ object not iterable

What is a TypeError?

A TypeError occurs when we try to perform an operation on the wrong type of object. For example, if we try to calculate the square root of a list instead of an integer or a floating-point number, then a TypeError will be generated by the Python interpreter.

Difference Between a Float and an Iterable

Iterables are containers that can store multiple values and return them one by one. Iterables can store any number of values, and the values can either be the same type or different types. You can go to the next item in an iterable object using the next() method.

A floating-point number is any number with a decimal point. You can define a floating-point number in Python by defining a variable and assigning a decimal point number to it.

x = 4.2

print(type(x))
class 'float'

Floating-point numbers do not store multiple values like a list or a dictionary. If you try to iterate over a float, you will raise the error “TypeError: ‘float’ object is not iterable” because float does not support iteration.

You will get a similar error if you try to iterate over an integer or a NoneType object.

Example #1: Iterate Over a Floating Point Number

Let’s look at an example where we initialize a floating-point number and iterate over it.

# Define floating point number

float_num = 10.0 

# Iterate over the floating point number

for num in float_num:

    print(num)

Let’s see what happens when we run the code:

TypeError                                 Traceback (most recent call last)
      1 for num in float_num:
      2     print(num)
      3 

TypeError: 'float' object is not iterable

We raise the error because Python does not support iteration on a floating-point number.

Solution #1: Convert float to string Using the str() Method

The first solution involves converting the float_num object to a string using the str() method and iterating over every digit. We can do iteration over a string because the string type is iterable. However, the for loop will return each character of the float_num string.

# Define floating point number

float_num = 10.0 

# Iterate over the floating point number

for digit in str(float_num):

    print(digit)

Solution #2: Iterate Using the range() Method

To print the range of numbers, we can use the int() method to convert the number to an integer and then use the integer as input to the range() method. The range() method only accepts integer numbers, in which case we have to convert any floating-point number that we want to iterate over to an integer. The range() method returns an iterable object which we can iterate over using a for loop.

# Define floating point number

float_num = 30.0 

# Convert the float number to an integer

int_num = int(float_num)

# Iterate over the floating point number

for num in range(int_num):

    print(num)

Let’s see what happens when we run the revised code:

0
1
2
3
4
5
6
7
8
9

Example #2: Determine if a Number is Prime

Let’s look at another example where we write a program to check if a number entered by the user is prime or not. Prime numbers are only divisible by themselves, and 1. To start, we will ask the user to insert the number to determine whether it is prime or not.

number = float(input("Enter a number:  "))

Then we define a function that determines whether the number is prime by using the modulo operator %. If the remained of x % y equals zero, then y is a factor of x. Prime numbers have two factors, one and itself.

# Function to determine if number is prime or not

def prime_number_calc(num):

    for i in num:
        # Ensure we do not divide the number by zero or one

        if i > 1:

            if num % i == 0:

                 print(f'{num} is not prime')

                 break

    # If the loop runs completely the number is prime

    else:

        print(f'{num} is a prime number')
prime_number_calc(number)

Let’s run the code to see what happens:

TypeError                                 Traceback (most recent call last)
      1 def prime_number_calc(num):
      2     for i in num:
      3         if i > 1:
      4             if num % i == 0:
      5                 print(f'{num} is not prime')

TypeError: 'float' object is not iterable

The Python interpreter throws the TypeError because a floating-point number is not a suitable type to iterate over. A for loop requires an iterable object to loop over.

Solution

To solve this problem, we need to convert the input number to an integer using int() and pass the integer the range() method instead of the float. Let’s look at the revised code:

def prime_number_calc(num):

     for i in range(int(num)):

         if i > 1:

             if num % i == 0:

                 print(f'{num} is not prime')

                 break
     else:

         print(f'{num} is a prime number')
number = float(input("Enter a number:  "))

prime_number_calc(number)

Let’s run the code to see what happens:

Enter a number:  17.0

17.0 is a prime number

Our code successfully prints the result that 17.0 is a prime number.

Summary

Congratulations on reading to the end of this tutorial. The error “TypeError: ‘float’ object is not iterable” occurs when you try to iterate over a floating-point number as if it were an iterable object like a list.

You must use the range() method to iterate over a collection of numbers. However, you must convert the float to an integer beforehand passing it to the range() method. If you want to iterate over the digits of the float, you can convert the float to a string and use the range() function.

To learn more about Python for data science and machine learning, go to the online courses pages on Python for the best courses online!

Have fun and happy researching!

One error that you might encounter when coding in Python is:

TypeError: 'float' object is not iterable

This error usually occurs when you pass a float object into a function or syntax where an iterable is expected. There are three common scenarios in which this error occurs:

  1. Using a float in a for loop
  2. Call list() with float objects
  3. Call the sum() function and pass float objects

This tutorial shows you examples that cause this error and how to fix it.

1. Using a float in a for loop

One common cause of this error is when you pass a float when attempting to iterate using a for loop.

Suppose you have a for loop code as follows:

num = 4.5

for i in num:
    print(i)

The num variable is a float object, so it’s not iterable and causes the following error when used in a for loop:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    for i in num:
TypeError: 'float' object is not iterable

A for loop requires you to pass an iterable object, such as a list or a range object.

If you want to use a float, you need to convert it to an int using the int() function, then convert it to a range with range() as follows:

num = 4.5

for i in range(int(num)):
    print(i)

Output:

Unlike the for loop in other programming languages where you can use an integer value, the for loop in Python requires you to pass an iterable. Both int and float objects are not iterable.

2. Call list() with float objects

This error also occurs when you call the list() function and pass float objects to it.

Suppose you want to create a list from float values as follows:

num = 4.5

my_list = list(num)

Python shows “TypeError: ‘float’ object is not iterable” because you can’t pass a float when creating a list.

To create a list from a float, you need to surround the argument in square brackets:

num = 4.5

my_list = list([num])

print(my_list)  # [4.5]

The same error also occurs when you create a dictionary, tuple, or set using a float object. You need to use the appropriate syntax for each function:

num = 5.5

# Float to dictionary
val = dict(num=num)
print(val)  # {'num': 5.5}

# Float to tuple
val = tuple([num])
print(val)  # (5.5,)

# Float to set
val = set([num])
print(val)  # {5.5}

For the dict() function, you need to pass arguments in the form of key=value for the key-value pair.

3. Call the sum() function and pass float objects

Another condition where this error might occur is when you call the sum() function and pass float objects to it.

Suppose you try to sum floating numbers as shown below:

x = 4.5
y = 6.8

z = sum(x, y)

You’ll get “float is not iterable” error because the sum() function expects a list.

To fix this, surround the arguments you passed to sum() with square brackets as follows:

x = 4.5
y = 6.8

z = sum([x, y])

print(z)  # 11.3

Notice how the sum function works without any error this time.

Conclusion

The Python error “‘float’ object is not iterable” occurs when you pass a float object when an iterable is expected.

To fix this error, you need to correct the assignments in your code so that you don’t pass a float in place of an iterable, such as a list or a range.

If you’re using a float in a for loop, you can use the range() and int() functions to convert that float into a range. You can also convert a float into a list by adding square brackets [] around the float objects.

I hope this tutorial is helpful. Happy coding! 👍

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”.

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.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

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

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

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:

factor = float(input("Enter a number: "))

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:

for n in factor:
	if factor % n == 0:
		print("{} is a factor of {}.".format(factor, n))

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:

Enter a number: 8
Traceback (most recent call last):
  File "main.py", line 3, in <module>
	for n in factor:
TypeError: 'float' object is not iterable

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:

for n in range(1, int(factor) + 1):
	if factor % n == 0:
		print("{} is a factor of {}.".format(factor, n))

Our range() statement generates a list of numbers between one and the value of “factor” plus one.

We have added 1 to the upper end of our range so that our “factor” number is considered a factor. Our for loop can then iterate over this list. We’ve converted “factor” to an integer in our code because the range() statement does not accept floating point numbers.

Run our code again and see what happens:

8.0 is a factor of 1.
8.0 is a factor of 2.
8.0 is a factor of 4.
8.0 is a factor of 8.

Our code successfully returns a list of all the factors of the number we inserted into our program.

Conclusion

The Python “TypeError: ‘float’ object not iterable” error is caused when you try to iterate over a floating point number as if it were an iterable object, like a list or a dictionary.

To solve this error, use a range() statement if you want to iterate over a number. A range statement generates a list of numbers in a given range upon which a for loop can iterate.

Now you’re ready to fix this common Python error in your code!

Float is an non iterable python datatype and typeerror float object is not iterable occurs only when any python statement invokes float as iterable element in loop etc. In this article, we will explore multiple scenarios where we face this error. We will understand the root cause of this error and apply the same to fix different scenarios.

Typeerror float object is not iterable ( Deep Dive in Root Cause ) –

Usually we run the loop over iterable objects. In each iteration , It returns next value for the sequence. Like list, dict, tuple are iterable object. But float is not iterable object. Its single value element. Lets see with code for more clarity-

element= 7.5
for i in element:
  print(i)

Typeerror float object is not iterable

Typeerror float object is not iterable

How to check float is iterable or not ?

If any python object is iterable then its override the method __iter__() in its class and the best way to check the same is using dir() function.

print(dir(float))

Output –

['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']

Since __iter__() is missing hence float is not iterable object

There are infinite business logic where we face this error. But developer intention and root cause for this error is common everywhere. In this section lets understand the same.

Case 1 : Solution for looping scenario using range –

Usually when we want to loop any logic, we need to define the counter and there if we pass float we get this error. The straight fix for this using range. Basically range converts number to an iterable list. But make sure range only accepts interger values so if we pass float directly into range function we get this error – Typeerror: float object cannot be interpreted as an integer . Hence we will convert the float to int and then pass in range() function. Here is the implementation-

element= 7.5
for i in range(int(element)):
  print(i)

float object is not iterable range()

float object is not iterable range()

Case 2 : Float iteration as str object –

As you know str objects in python are iterable. In some scenarios developer needs to iterate Float object as string only. But they somehow forgot to typecast the float object into str . Hence they get this error.

element= 7.5
for i in str(element):
  print(i)

float object is not iterable fix by str()

float object is not iterable fix by str()

Here interpreter is iterating over the digits of float object as string.

Similar Typeerror on Iterable objects –

Just like Float, int and NoneType objects are not iterables. These error are similar to each others but occurs in different business logics. You can read more about them here-

Typeerror nonetype object is not iterable : Complete Solution

Typeerror int object is not iterable : Root cause and Fix

Thanks 

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Понравилась статья? Поделить с друзьями:
  • Fondital antea ошибка е52
  • Fonbet код ошибки 101
  • Fona x70 ошибка a02
  • Fona x70 коды ошибок
  • Following deviation is too large ошибка