Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you convert values to floats?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

How do you turn all items in a list into a string?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

Can you have a list of floats in Python?

For creating a list of floats in python, we need a for loop to iterate throughout the list. Also, use the append for creating a new list. After writing the above code (create a list of floats), Ones you will print (list_of_floats) then the output will appear as a “[1.1, 3.5, 7.6]” as a float value.


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


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


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

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

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.


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


You can use numpy to convert a list directly to a floating array or matrix.

    import numpy as np
    list_ex = [1, 0] # This a list
    list_int = np.array(list_ex) # This is a numpy integer array

If you want to convert the integer array to a floating array then add 0. to it

    list_float = np.array(list_ex) + 0. # This is a numpy floating array