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

The best answers to the question “In Python, how do I convert all of the items in a list to floats?” in the category Dev.


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:

my_list = ['0.49', '0.54', '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 my_list:

But this doesn’t seem to work for me.


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


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


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:

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.


This would be an other method (without using any loop!):

import numpy as np