Python Create List From Range

πŸ’‘ Problem Formulation: In many Python programming scenarios, you may need to generate a list of contiguous numbers. For instance, you might want to create a list containing all integers from, say, 10 to 20. The desired output for this input would be [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20].

This article explores various methods to create such a list from a specified range.

Method 1: Using range() with list()

One of the simplest methods to create a list from a range in Python is to use the built-in range() function wrapped by the list() function. The range() function returns a sequence of numbers, which list() then converts into a list.

Here’s an example:

numbers_list = list(range(10, 21))
print(numbers_list)
# [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Examples

The code starts by calling range(10, 21) which generates a sequence from 10 to 20, as the upper limit is non-inclusive. Wrapping this with list() converts the sequence into a list, which is then stored in the variable numbers_list.

Note that the range() function’s first argument is included and the second argument is excluded in the final series. πŸ‘‡πŸ‘‡πŸ‘‡

Here are three examples to illustrate how the range() function works in Python, highlighting the inclusion of the first argument and the exclusion of the second argument:

  • Example 1: When we use range(0, 5), it generates a series starting from 0 and ends before 5, resulting in [0, 1, 2, 3, 4].
  • Example 2: For range(3, 8), the series starts from 3 and ends before 8, giving us [3, 4, 5, 6, 7].
  • Example 3: With range(1, 10, 2), it starts from 1 and increments by 2 until it reaches or exceeds 10, so we get [1, 3, 5, 7, 9].

In each case, the start of the range is included, while the end is excluded, demonstrating the behavior of the range() function.

Method 2: Using a List Comprehension

A list comprehension is a concise way to create lists. It consists of brackets containing an expression followed by a for clause. This method is more flexible than the first as it allows the inclusion of conditional logic within the list creation.

Here’s an example:

numbers_list = [x for x in range(10, 21)]
print(numbers_list)

Output:

This single line of code iterates over each number x in the sequence generated by range(10, 21) and includes it in the new list numbers_list.

Method 3: Using itertools.islice()

The itertools module contains a function called islice() which can be used to slice a sequence. This is particularly useful when dealing with very large ranges as it doesn’t require generating the whole range at once.

Here’s an example:

import itertools

numbers_iterator = range(10, 1000000)  # Imagine a very long range here.
numbers_list = list(itertools.islice(numbers_iterator, 0, 11))
print(numbers_list)

In this example, numbers_iterator is an iterator over a very large range. Then islice() is used to extract only the first 11 elements from this iterator and converts them into a list.

Method 4: Using a for Loop

Sometimes you may need to generate a list with more complex logic, where neither list comprehensions nor the range() function are adequate. A for loop provides utmost flexibility at the expense of brevity.

Here’s an example:

numbers_list = []
for i in range(10, 21):
    numbers_list.append(i)
print(numbers_list)

This example creates an empty list and appends each number from the range(10, 21) sequentially, resulting in the desired list of numbers.

Bonus One-Liner Method 5: Using a Generator Expression

Generator expressions are similar to list comprehensions but they don’t create the list in memory. This means they can be more efficient when the list comprehension would generate a large list that is only needed once.

Here’s an example:

numbers_generator = (x for x in range(10, 21))
numbers_list = list(numbers_generator)
print(numbers_list)

This code creates a generator expression (x for x in range(10, 21)) that generates numbers on-the-fly and then converts them into a list with list().

Summary/Discussion

  • Using range() with list(): Straightforward and ideal for simple ranges; lacks flexibility in list manipulation.
  • Using a List Comprehension: Compact and allows inline conditional logic; a bit less readable for complex conditions.
  • Using itertools.islice(): Perfect for slicing large ranges without consuming much memory; adds a dependency on itertools.
  • Using a for Loop: Most versatile and easy to understand; could become verbose for very simple cases.
  • Using a Generator Expression: Efficient for large lists when the list is used only once; slightly less intuitive than list comprehensions.

In summary, list(range()) is perfect for most cases due to its simplicity and readability.


Check out my free email list by downloading our Python cheat sheets here: