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
In the following examples, we cover different approaches on creating a list from 1 to n.
1. Create list from 1 to n using For Loop and Range in Python
In the following program, we create a list with numbers from 1 to n=12, using Python For Loop and Python Range object.
Steps
- Take the value of n in a variable.
n = 12
- Take an empty list to store the generated list.
output = []
- Write a For loop that iterates over the sequence of numbers in the range that starts at 1 and stops at n.
for i in range(1, n+1):
- Inside the For loop, append the element from the range to the output list.
output.append(i)
After the loop is done executing, we have a list of numbers from 1 to n in the output list.
Program
The complete program to generate a list of numbers from 1 to n using For loop and range.
Python Program
# Take n value
n = 12
# Take an empty list to store the generated sequence
output = []
# Generate the sequence of numbers from 1 to n
for i in range(1, n+1):
output.append(i)
print(output)
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.
This is like a concise version of the previous approach.
Python Program
# Take n value
n = 12
# Generate list from 1 to n using list comprehension
output = [i for i in range(1, n+1)]
# Print the list
print(output)
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.