Open In App

Convert Float String List to Float Values-Python

Last Updated : 05 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of converting a list of float strings to float values in Python involves changing the elements of the list, which are originally represented as strings, into their corresponding float data type. For example, given a list a = [‘87.6’, ‘454.6’, ‘9.34’, ’23’, ‘12.3’], the goal is to convert each string into a float, resulting in the list [87.6, 454.6, 9.34, 23.0, 12.3].

Using list comprehension

List comprehension provides a concise way to convert each string in the list to a float. It uses a single line of code with a clear syntax, making it both readable and efficient. This method is ideal for quick data transformations and is faster than traditional loops due to optimized internal implementation.

Python
a = ['87.6', '454.6', '9.34', '23', '12.3']

res = [float(ele) for ele in a]
print(res)

Output
[87.6, 454.6, 9.34, 23.0, 12.3]

Explanation: List comprehension iterates through a, converts each string to a float, stores the results in res.

Using map()

map() applies a specified function to each item in an iterable, such as a list. It returns an iterator, which can be converted to a list for easy access. It is memory-efficient and performs well with large datasets because it processes items lazily without creating intermediate data structures.

Python
a = ['87.6', '454.6', '9.34', '23', '12.3']

res= list(map(float, a))
print(res)

Output
[87.6, 454.6, 9.34, 23.0, 12.3]

Explanation: map() applies the float function to each element in a, converts the strings to floats and stores the results in res.

Using numpy

NumPy’s array() allows us to convert a list of float strings directly into a NumPy array with a specified data type, like float. This method is highly efficient for numerical operations, especially when working with large datasets, as NumPy is optimized for performance in mathematical computations and array manipulations

Python
import numpy as np
a = ['87.6', '454.6', '9.34', '23', '12.3']

res = np.array(a, dtype=float)
print(res)

Output
[ 87.6  454.6    9.34  23.    12.3 ]

Explanation: np.array() converts the list a to a NumPy array with the float data type and stores the result in res .

Using for loop

A traditional for loop iterates through each element in the list, converts the string to a float and appends the result to a new list. While it’s longer compared to list comprehension or map(), this method provides clear step-by-step control, making it easier to understand for beginners or when additional processing is required during iteration.

Python
a = ['87.6', '454.6', '9.34', '23', '12.3']

res = []
for ele in a:
    res.append(float(ele))
print(res)

Output
[87.6, 454.6, 9.34, 23.0, 12.3]

Explanation: for loop iterates through each element in a, converts it to a float, appends it to the res list.



Next Article
Practice Tags :

Similar Reads