Contents
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 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 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.
Related Tutorials
- Python List with First N Elements
- How to Insert Item at Specific Index in Python List?
- Python – List of Strings
- How to Get List of all Files in Directory and Sub-directories?
- How to Access List Items in Python?
- Python List of Functions
- Shuffle Python List
- Python – Check if List Contains all Elements of Another List
- How to Append List to Another List in Python? – list.extend(list)
- Python – Count the items with a specific value in the List