List of Numbers From 1 to N in Python
 Create a UserDefined Function to Create a List of Numbers From 1 to N

Use the
range()
Function to Create a List of Numbers From 1 to N 
Use the
numpy.arange()
to Create a List of Numbers From 1 to N
This tutorial will discuss how to create a list of numbers from 1 to some specified number.
Create a UserDefined Function to Create a List of Numbers From 1 to N
This method will take the required number from the user and iterate till that number using the for
loop. In each iteration, we will increment the value and append the number to a list.
The following code will explain this.
def createList(n):
lst = []
for i in range(n+1):
lst.append(i)
return(lst)
print(createList(10))
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Use the range()
Function to Create a List of Numbers From 1 to N
The range()
function is very commonly used in Python. It returns a sequence between two numbers given in the function arguments. The starting number is 0 by default if not specified. It also has a parameter called step
, which can specify the incrementation and is one by default.
In the code below, we will generate a list of numbers using this function.
lst = list(range(1,10+1))
print(lst)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Note the use of the list()
function. It ensures that the final result is in a list form. Also, notice the use of +1
, which ensures that the final number is also included in the list.
We can also use the list comprehension method with the range()
function. List Comprehension is a simple, concise way of creating a list in Python.
This method is shown below:
lst = [i for i in range(1,10+1)]
print(lst)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Use the numpy.arange()
to Create a List of Numbers From 1 to N
The NumPy
module has many useful methods to create and modify arrays. The arange()
function from this module is similar to the range()
function discussed earlier. The final output is a numpy array.
We will implement this function in the code below.
import numpy as np
lst = list(np.arange(1,10+1))
print(lst)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
We also use the list()
function to convert the final output to a list form.
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedIn