TechieClues TechieClues
Updated date Mar 28, 2024
This blog explores two efficient methods to convert a list of strings to a list of float values in Python.

Method 1: Using a for loop and the float() function

The first method to convert a list of strings to float is by using a for loop and the built-in float() function in Python. The for loop iterates through each element in the list and converts the string to float using the float() function.

# Program to convert a list of strings to float
string_list = ['2.5', '3.7', '4.8', '1.9']

# Creating an empty list to store the float values
float_list = []

# Converting each string element to float and adding to the float list
for i in string_list:
    float_list.append(float(i))

# Printing the float list
print(float_list)

Output:

[2.5, 3.7, 4.8, 1.9]

In the above program, we have defined a list of strings called string_list. We have created an empty list called float_list to store the float values. Then we have used a for loop to iterate through each element in the string_list. Inside the for loop, we have converted each string element to float using the built-in float() function and added the float value to the float_list. Finally, we have printed the float_list, which contains the converted float values.

Method 2: Using list comprehension and the float() function

To convert a list of strings to float is by using list comprehension and the float() function in Python. List comprehension is a concise way to create lists in Python. It provides a more efficient way to write the same code as in the previous method. 

# Program to convert a list of strings to float using list comprehension
string_list = ['2.5', '3.7', '4.8', '1.9']

# Converting each string element to float using list comprehension
float_list = [float(i) for i in string_list]

# Printing the float list
print(float_list)

Output:

[2.5, 3.7, 4.8, 1.9]

In the above program, we have defined a list of strings called string_list. We have used list comprehension to create a new list called float_list. Inside the list comprehension, we have used the float() function to convert each string element to float. Finally, we have printed the float_list, which contains the converted float values.

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!