Skip to content

In Python, how do I convert all of the items in a list to floats?

You can use a for loop and the float() function to convert each item in a list to a float. Here is an example:

Using a for loop and float() function to convert each item in a list to a float

python
numbers = ['1', '2', '3', '4']

for i in range(len(numbers)):
    numbers[i] = float(numbers[i])

print(numbers)

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

Alternatively, you can use a list comprehension to achieve the same result:

Use a list comprehension to convert each item in a list to a float

python
numbers = ['1', '2', '3', '4']
numbers = [float(x) for x in numbers]
print(numbers)

Both of the above code snippet will give you the same output [1.0, 2.0, 3.0, 4.0]

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.