6

I'm writing a script to return a number to a certain amount of significant figures. I need to turn a float into a list so that I can change the number easily. This is my code:

def sf(n,x):
    try:
        float(n)
        isnumber = True
    except ValueError:
        isnumber = False
    if isnumber == True:
        n = float(n)
        n = list(n)
        print(n)
    else:
        print("The number you typed isn't a proper number.")
sf(4290,2)

This returns the error:

Traceback (most recent call last):
File "/Users/jacobgarby/PycharmProjects/untitled/py package/1.py", line 29, in <module>
sf(4290,2)
File "/Users/jacobgarby/PycharmProjects/untitled/py package/1.py", line 25, in sf
n = list(n)
TypeError: 'float' object is not iterable

What does this error mean, and how can I stop it from happening?

UpAndAdam
  • 4,515
  • 3
  • 28
  • 46
user3324655
  • 83
  • 1
  • 1
  • 4
  • 2
    What do you expect a list made from a float to look like? There is no obvious way to convert these (at least to me). Which is essentially why this conversion doesn't work by default – camz May 27 '15 at 15:31
  • 3
    Try `list(str(n))` or if you need the number values `[int(x) for x in str(n)]` – kylieCatt May 27 '15 at 15:32
  • May be relevant: http://stackoverflow.com/questions/3410976/how-to-round-a-number-to-significant-figures-in-python – camz May 27 '15 at 15:35
  • Is this homework? Turn a float into a list doesn't sound like homework, but I don't understand why else you would use a method like this to format a float... – Two-Bit Alchemist May 27 '15 at 15:46

5 Answers5

10

You can call it like list([iterable]), so the optional needs to be iterable, which float isn't.

iterable may be either a sequence, a container that supports iteration, or an iterator object.

The direct definition as list would work though:

n = [float(n)]
tynn
  • 38,113
  • 8
  • 108
  • 143
2

Function to cast ANYTHING to list

I wrote a function, which cast anything (at least the types I need) to a list. So just replace your line n = list(n) by n=castToList(n). I use it for pandas DataFrames to ensure columns containing only lists.

Demo:

In [99]: print( castToList([1,2]))
[1, 2]

In [100]: print( castToList(np.nan))
[nan]

In [101]: print( castToList('test'))
['test']

In [102]: print( castToList([1,2,'test',7.3,np.nan]))
[1, 2, 'test', 7.3, nan]

In [103]: print( castToList(np.array([1,2,3])) )
[1, 2, 3]

In [104]: print( castToList(pd.Series([5,6,99])))
[5, 6, 99]

Code:

def castToList(x): #casts x to a list
    if isinstance(x, list):
        return x
    elif isinstance(x, str):
        return [x]
    try:
        return list(x)
    except TypeError:
        return [x]


import numpy as np
import pandas as pd
print( castToList([1,2]))
print( castToList(np.nan))
print( castToList('test'))
print( castToList([1,2,'test',7.3,np.nan]))
print( castToList(np.array([1,2,3])) )
print( castToList(pd.Series([5,6,99])))
Markus Dutschke
  • 9,341
  • 4
  • 63
  • 58
1
def sf(n,x):
    try:
        float(n)
        isnumber = True
    except ValueError:
        isnumber = False
    if isnumber == True:
        n = float(n)
        n = [n]
        print(n)
    else:
        print("The number you typed isn't a proper number.")
Alex Kashin
  • 575
  • 6
  • 13
0

I made a function that does that

def f_to_list(f_variable,num_algorism):
    list1 = []
    n = 0
    variable2 = str(f_variable)
    for i in variable2 :
        list1 += i
    if list1[(num_algorism-1)] == '.' :
        print('banana')
        num_algorism +=1
    list1 = list1[0:(num_algorism )]
    print(list1)

hope this helps.

wp78de
  • 18,207
  • 7
  • 43
  • 71
Ragoniis
  • 29
  • 3
-1

Try to convert it into an iterable as the error is suggesting that. An iterable is something of which you can access the i'th element. You can't do that for int,float etc. Python has list and str for that.

so convert it into list(obj) and iter or str(obj)

therealprashant
  • 701
  • 15
  • 27
  • 1
    The converting to list or iter won't help here. Converting a float to list is what the original error is caused by. String may be useful, depending on the use – camz May 27 '15 at 15:37
  • Your answer suggests iterables can be randomly accessed by index. An arbitrary iterable **can't** be accessed randomly. You can only get the next element from it, one after another, once. Not that you can turn a float value into an iterable *anyway*, that's what the error message tells you. Not trying to treat a single float number as a sequence or series or iterable would be a much better approach. – Martijn Pieters Aug 21 '19 at 15:44