tags:

views:

220

answers:

3

I have a script which reads a text file, and 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 value in the list from a string to a floating point.

I have tried

for item in list:
    float(item)

But this doesn't seem to work for me...

+15  A: 
[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.

SilentGhost
+11  A: 

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

Tim Pietzcker
+1 for the usage of the word 'pythonic'
Andrew Song
A: 

float(item) do the right thing: it converts its argument to float and and return it, but it doesn't change argument in-place. A simple fix for your code is:

new_list = []
for item in list:
    new_list.append(float(item))

The same code can written shorter using list comprehension: new_list = [float(i) for i in list]

To change list in-place:

for index, item in enumerate(list):
    list[index] = float(item)

BTW, avoid using list for your variables, since it masquerades built-in function with the same name.

Denis Otkidach