346

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:
    float(item)

But this doesn't seem to work for me.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158

14 Answers14

615
[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
  • 307,395
  • 66
  • 306
  • 293
  • 14
    For large array's, I would recommend using numpy: `np.array(inp_list, dtype=np.float32)`. You don't even have to specify if it's a float and just use: `np.array(inp_list)` – Thomas Devoogdt May 23 '18 at 13:40
  • 2
    @Thomas Devoogdt : I think you do need to specify the type, otherwise you will get a numpy array of strings – seb007 Jul 02 '19 at 09:28
  • 8
    Please note that you have to assign `[float(i) for i in lst]` to something. E.g.: `new_list = [float(i) for i in lst]` – FaizFizy Oct 24 '19 at 02:27
  • Why doesn't python have a professional function to perform this operation? – user2585501 Oct 07 '21 at 00:17
  • Depending on your security expectations, you might as well just "eval" like `eval(my_list.join(", "))` – Raul Aug 22 '23 at 15:38
160

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
  • 328,213
  • 58
  • 503
  • 561
35

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

import numpy as np
list(np.float_(list_name))
Amin Kiany
  • 722
  • 8
  • 17
  • 2
    Don't need to cast the np.array into the list again if you like to keep it as an np.array =) – alvas Jun 19 '18 at 01:49
17

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
  • 32,032
  • 8
  • 79
  • 100
  • Sorry, I did not get what in-place means here. How does it differ from the previous pythonic answer. Doesn't the conversion in the previous answer "[float(i) for i in lst]" retain the original list index – AAI Jan 29 '18 at 17:34
  • 2
    @AAI Change original list vs. create a new one. – Denis Otkidach Jan 31 '18 at 04:05
15

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

Alireza
  • 806
  • 1
  • 8
  • 10
7

You can use the map() function to convert the list directly to floats:

float_list = map(float, list)
mnaghd01
  • 125
  • 2
  • 6
3

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
bfree67
  • 669
  • 7
  • 6
2

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'>
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Samlex
  • 161
  • 3
  • 8
2

you can use numpy to avoid looping:

import numpy as np
list(np.array(my_list).astype(float)
vitorrr
  • 46
  • 2
  • 1
    Why would you use your approach rather than `import numpy as np list(np.float_(list_name))` from the answer above? – jared_mamrot Jul 09 '20 at 01:15
1
newlist = list(map(float, mylist))
Aruz
  • 41
  • 7
0
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'>
0

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)
Max Kleiner
  • 1,442
  • 1
  • 13
  • 14
0
for i in range(len(list)): list[i]=float(list[i])
double-beep
  • 5,031
  • 17
  • 33
  • 41
-1

I have solve this problem in my program using:

number_input = float("{:.1f}".format(float(input())))
list.append(number_input)
sentence
  • 8,213
  • 4
  • 31
  • 40
Gui
  • 1
  • 1
    The OP states that he is reading from a text file. this answer does not apply to what has been asked. – Ilhicas Sep 04 '18 at 13:57