Create List of Numbers with Given Range - Python
The task of creating a list of numbers within a given range involves generating a sequence of integers that starts from a specified starting point and ends just before a given endpoint. For example, if the range is from 0 to 10, the resulting list would contain the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9.
Using range()
range() generates an iterator that produces numbers within a specified range. It is highly efficient as it doesn’t create the entire list upfront, making it memory-friendly. Converting the iterator to a list gives us the full range of numbers.
r1 = 0
r2 = 10
li = list(range(r1,r2))
print(li)
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Explanation: list(range(r1, r2)) creates a sequence of numbers from r1 to r2 using range() and converts it into a list li with list().
Using list comprehension
List comprehension is a concise and efficient way to create lists by iterating over an iterable like range(), in a single line. It simplifies code by eliminating the need for explicit for loops and append() calls.
r1 = 0
r2 = 10
li = [i for i in range(r1, r2)]
print(li)
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Explanation: list comprehension iterates through a sequence of numbers generated by range(r1, r2), which starts at r1 and ends at r2 . Each number in this range is added to the list li.
Using numpy.arange()
numpy.arange() from the NumPy library that generates an array of evenly spaced values over a specified range. It is highly efficient for creating large sequences of numbers, particularly when performing numerical computations or working with multidimensional data.
import numpy as np
r1 = 0
r2 = 10
li = np.arange(r1, r2).tolist()
print(li)
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Explanation: np.arange(r1, r2).tolist() uses NumPy's arange() function to generate a sequence of numbers from r1 o r2 .tolist() method converts the NumPy array into a Python list.
Using itertools.count()
itertools.count() creates an infinite sequence starting from a specified number. When combined with itertools.islice(), it can generate a finite range by limiting the count to a specific number of elements.
import itertools
r1 = 0
r2 = 10
li = list(itertools.islice(itertools.count(r1), r2 - r1))
print(li)
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Explanation: list(itertools.islice(itertools.count(r1), r2 - r1)) generates a sequence starting from r1 using itertools.count(r1), slices it to include the first r2 - r1 numbers and converts the result into a list.
Related Articles: