In Python, how do I convert all of the items in a list to floats?


Question

I have a script which reads a text file, pulls decimal numbers out of it as strings and places them into a list.

So I have this list:

['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54', '0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54']

How do I convert each of the values in the list from a string to a float?

I have tried:

for item in list:
    float(item)

But this doesn't seem to work for me.

1
196
2/25/2018 10:21:54 AM

Accepted Answer

[float(i) for i in lst]

to be precise, it creates a new list with float values. Unlike the map approach it will work in py3k.

366
10/23/2009 3:34:28 PM

map(float, mylist) should do it.

(In Python 3, map ceases to return a list object, so if you want a new list and not just something to iterate over, you either need list(map(float, mylist) - or use SilentGhost's answer which arguably is more pythonic.)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon