Python - Convert List of strings into List of floats
Python - Convert List of strings into List of floats
To convert a given list of strings into a list of floats in Python, you can use List comprehension or For loop to iterate over the elements, and then use float() built-in function to convert each string element to a floating point element.
Now, we shall go through some examples of converting a given list of strings into list of floats using list comprehension, or a For loop.
1. Converting list of strings into list of floats using List comprehension and float()
Consider that we are given a list of string elements, and we have to convert them into a list of floats using List comprehension and float() builtin function.
Steps
- Given a list of strings in my_list.
- Use list comprehension, and for each element in the original list, apply float() function to the element.
[float(x) for x in my_list]
- The above expression returns a list of floats created from the original list. You may store it in a variable, say list_float.
- You may print the resulting floating point list to the standard output using print() statement.
Program
The complete program to convert the given list of strings into a list of floats using List comprehension and float() built-in function.
Python Program
# Given a list of strings
my_list = ['1.23', '2.05', '3.14', '4.7']
# Convert list of strings into list of floats
list_float = [float(x) for x in my_list]
print(list_float)
Output
[1.23, 2.05, 3.14, 4.7]
2. Converting list of strings into list of floats using For loop and float()
Consider that we are given a list of string elements, and we have to convert them into a list of floats.
Steps
- Given a list of strings in my_list.
- Take an empty list to store the resulting list of floating point values, say list_float.
- Use a For loop to iterate over the given list, and for each element in the given list, convert the string element into a float value, and append the float value to list_float using list append() method.
for x in my_list:
list_int.append(float(x))
- After the For loop is done, list_int contains the respective integer values created from the original list.
Program
The complete program to convert the given list of strings into a list of integers using For loop, list append() function, and float() built-in function.
Python Program
# Given a list of strings
my_list = ['1.23', '2.05', '3.14', '4.7']
# Take an empty list to store the float values
list_float = []
# Convert list of strings into list of floats
for x in my_list:
list_float.append(float(x))
print(list_float)
Output
[1.23, 2.05, 3.14, 4.7]
Summary
In this tutorial, we have seen how to convert a given list of strings into a list of floats, with examples.