How to Convert a List to a Float in Python?

Estimated read time 1 min read

To convert a list of numbers to a list of floats in Python, you can use list comprehension. Here’s an example:

my_list = [1, 2, 3, 4, 5]

float_list = [float(num) for num in my_list]


In the example above, we have a list called my_list containing integers. To convert each element in the list to a float, we use list comprehension. The expression float(num) converts each num in my_list to a float. The resulting list of floats is stored in the float_list variable.

Note that if the original list contains elements that are already floats, they will remain unchanged in the converted list. The conversion to float will only affect non-float elements in the list.

You can apply the same approach to convert a list of strings representing numbers to a list of floats. For example:

string_list = ['1.2', '3.4', '5.6']

float_list = [float(num) for num in string_list]


In this case, the list comprehension converts each string element in string_list to a float using the float() function.

By using list comprehension, you can easily convert a list of numbers or strings to a list of floats in Python.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply