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.
Pythonr1=0r2=10li=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 r2using 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.
Pythonr1=0r2=10li=[iforiinrange(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 atr1 and ends atr2. Each number in this range is added to the listli.
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.
Pythonimportnumpyasnpr1=0r2=10li=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 withitertools.islice(), it can generate a finite range by limiting the count to a specific number of elements.
Pythonimportitertoolsr1=0r2=10li=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 usingitertools.count(r1), slices it to include the firstr2 - r1 numbers and converts the result into a list.
Related Articles:
Python program to create list of numbers with the given range