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

ID : 10270

viewed : 32

Tags : pythonlistcasting

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

vote vote

99

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

vote vote

89

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

vote vote

75

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

import numpy as np list(np.float_(list_name)) 
vote vote

68

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.

vote vote

58

you can even do this by numpy

import numpy as np np.array(your_list,dtype=float) 

this return np array of your list as float

you also can set 'dtype' as int

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

Related QUESTION?