Python: Create List from 1 to N

5/5 - (2 votes)

Creating a list containing a range of numbers from 1 to N in Python can be achieved through several methods. Here’s a concise list of alternative solutions:

  • Method 1: Using the range() function with a list comprehension.
  • Method 2: Utilizing the range() function with the list() constructor.
  • Method 3: Employing a loop to manually append numbers.

Method 1. List Comprehension with range()

N = 10
list_from_1_to_N = [i for i in range(1, N+1)]

This method utilizes list comprehension, a concise way to create lists. The range(1, N+1) generates numbers from 1 to N, and the list comprehension constructs a list from these numbers.

Method 2. list() Constructor with range()

N = 10
list_from_1_to_N = list(range(1, N+1))

The list() constructor is used to convert the range of numbers generated by range(1, N+1) into a list. It’s a straightforward approach, suitable for beginners.

Method 3. Looping and Appending

N = 10
list_from_1_to_N = []
for i in range(1, N+1):

In this method, a for loop iterates through each number generated by range(1, N+1), and each number is appended to the list manually. This approach is more verbose but illustrates the process of building a list step by step.

You can find more ways in this more comprehensive article:

πŸ‘‰ Python Create List from 1 to N