Creating a list of floats in Python can be done in several simple ways. The easiest way to create a list of floats is to define the numbers directly. Here’s how we can do it:
a = [0.1, 2.3, 4.5, 6.7]
print(a)
Output
[0.1, 2.3, 4.5, 6.7]
Using List Comprehension
List comprehension is a shorter way to create lists. It’s very useful when we need to perform an operation while creating the list. Here’s how we can create a list of float numbers:
a = [x * 0.5 for x in range(5)]
print(a)
Output
[0.0, 0.5, 1.0, 1.5, 2.0]
Using range() with map and lambda
If you want to create a list of floats based on a mathematical operation, map() combined with lambda can be efficient.
a = list(map(lambda x: x * 0.5, range(10)))
print(a)
Output
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
Using numpy (for large lists or more complex operations)
If you're dealing with a large number of floats or need specialized functionality like linspace, numpy is a highly optimized library for handling numerical operations.
import numpy as np
# List of 10 floats from 0.0 to 5.0
a = np.linspace(0.0, 5.0, num=10)
print(a)
Output
[0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778 3.33333333 3.88888889 4.44444444 5. ]