Python - How To Convert List to Float in Python

ID : 264

viewed : 70

Tags : PythonPython ListPython Float

vote vote

97

A list can store multiple elements of different data types. Due to this, we may encounter situations where we have to change the type of elements in the list. For example, we may have a list of strings, where each string is in the form of a float value.

In this tutorial, we will convert the elements of a list from a string to float in Python.

Use the for Loop to Convert All Items in a List to Float in Python

We can use the for loop to iterate through the list and convert each element to float type using the float() function.

We can then add each element to a new list using the append() function.

For example,

lst = ["1.5","2.0","2.5"]  float_lst = [] for item in lst:     float_lst.append(float(item))      print(float_lst) 

Output:

[1.5, 2.0, 2.5] 

Use the List Comprehension Method to Convert All Items in a List to Float in Python

The list comprehension method creates a new list in a single line of code. It achieves the same result but more compactly and elegantly.

For example,

lst = ["1.2", "3.4", "5.6"]  float_lst = [float(item) for item in lst]  print(float_lst) 

Output:

[1.5, 2.0, 2.5] 

Use the numpy.float_() Function to Convert Items in a List to Float in Python

The numpy.float_() function creates a numpy array with float values. We can pass the list to this function to create an array with float values. We can then convert this array to a list by using the list() function.

For example,

import numpy as np  lst = ["1.5","2.0","2.5"]  float_lst = list(np.float_(lst))      print(float_lst) 

Output:

[1.5, 2.0, 2.5] 

Use the numpy.array() Function to Convert Items in a List to Float in Python

This is similar to the previous method. Instead of using the numpy.float_() function, we will use the numpy.array() function and specify the dtype parameter as float.

See the code below.

import numpy as np  lst = ["1.5","2.0","2.5"]  float_lst = list(np.array(lst, dtype = 'float'))      print(float_lst) 

Output:

[1.5, 2.0, 2.5] 

  • Related HOW TO?