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

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.

This question is related to python list casting

The answer is


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


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

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

I have solve this problem in my program using:

number_input = float("{:.1f}".format(float(input())))
list.append(number_input)

I had to extract numbers first from a list of float strings:

   df4['sscore'] = df4['simscore'].str.findall('\d+\.\d+')

then each convert to a float:

   ad=[]
   for z in range(len(df4)):
      ad.append([float(i) for i in df4['sscore'][z]])

in the end assign all floats to a dataframe as float64:

   df4['fscore'] = np.array(ad,dtype=float)

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

This is how I would do it.

my_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']
print type(my_list[0]) # prints <type 'str'>
my_list = [float(i) for i in my_list]
print type(my_list[0]) # prints <type 'float'>

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


for i in range(len(list)): list[i]=float(list[i])

import numpy as np
my_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']
print(type(my_list), type(my_list[0]))   
# <class 'list'> <class 'str'>

which displays the type as a list of strings. You can convert this list to an array of floats simultaneously using numpy:

    my_list = np.array(my_list).astype(np.float)

    print(type(my_list), type(my_list[0]))  
    # <class 'numpy.ndarray'> <class 'numpy.float64'>

you can use numpy to avoid looping:

import numpy as np
list(np.array(my_list).astype(float)

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to casting

Subtracting 1 day from a timestamp date Cast object to interface in TypeScript TypeScript enum to object array Casting a number to a string in TypeScript Hive cast string to date dd-MM-yyyy Casting int to bool in C/C++ Swift double to string No function matches the given name and argument types C convert floating point to int PostgreSQL : cast string to date DD/MM/YYYY