Python – Create a list of numbers from 1 to n

Create a list of numbers from 1 to n

To create a list of numbers from 1 to n in Python, we can use For Loop with a range object, where range object starts at 1 and ends at n. During each iteration of the For Loop, we append the number from the range object into the list.

We can also make the code concise by using List Comprehension.

In this tutorial, we given examples using both the presentations. But, the way of using List Comprehension is recommended, as the code is relatively concise and pythonic.

Examples

1. Create list from 1 to n using For Loop and Range

In the following program, we create a list with numbers from 1 to n=12, using For Loop and Range object.

Python Program

n = 12
output = []

for i in range(1, n+1):
    output.append(i)

print(output)
Run Code Online

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

2. Create list from 1 to n using list comprehension

In the following program, we create a list with numbers from 1 to n=12, using List Comprehension.

Python Program

n = 12
output = [i for i in range(1, n+1)]
print(output)
Run Code Online

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Summary

In this tutorial of Python Examples, we learned how to create a list of numbers from 1 to n, with the help of well detailed examples.