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.
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
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">![]()
<span class="hidden md:block">Watch a video course</span>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
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]