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:
numbers = ['1', '2', '3', '4']
for i in range(len(numbers)):
numbers[i] = float(numbers[i])
print(numbers)
Watch a video course
Python - The Practical Guide
Alternatively, you can use a list comprehension to achieve the same result:
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]