ID : 264
viewed : 70
Tags : PythonPython ListPython Float
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.
for
Loop to Convert All Items in a List to Float in PythonWe 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]
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]
numpy.float_()
Function to Convert Items in a List to Float in PythonThe 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]
numpy.array()
Function to Convert Items in a List to Float in PythonThis 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]