To create a list with the numbers from 1 to n using Python, we can use the range() function in a custom Python function.

def listFrom1toN(n):
    return list(range(1,n+1))

print(listFrom1toN(13))

#Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

You can also use a loop to create a list from 1 to n in Python.

def listFrom1toN(n):
    list_from_1_to_n = []
    for x in range(1,n+1):
        list_from_1_to_n.append(x)
    return list_from_1_to_n

print(listFrom1toN(5))

#Output:
[1, 2, 3, 4, 5]

When working with numbers in a Python program, it’s possible you want to create an array from 1 to n in Python.

Arrays in Python are called lists, and we can easily create a list of the numbers 1 to n in our Python code.

The range() function takes in 3 arguments. The first is the starting point, the second is the ending point, and the third argument is the step size.

For example, if I want all the numbers between 1 and 10, I’d call the range function in the following way.

numbers_1_to_10 = list(range(1,11))

We can define a function which will create a list from 1 to n.

Below is an example of a function in Python which returns a list with numbers from 1 to n.

def listFrom1toN(n):
    return list(range(1,n+1))

print(listFrom1toN(13))

#Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

Using a Loop to Create a List from 1 to n in Python

We can also use a loop to create a list with the numbers from 1 to n in Python.

Let’s modify our function from above to use a loop to create a list from 1 to n. First, we need to initialize an empty list. Then we will loop over the numbers in the range from 1 to n, and append to our list.

Below is a function which will create and return a list from 1 to n with a for loop.

def listFrom1toN(n):
    list_from_1_to_n = []
    for x in range(1,n+1):
        list_from_1_to_n.append(x)
    return list_from_1_to_n

print(listFrom1toN(5))

#Output:
[1, 2, 3, 4, 5]

Hopefully this article has been useful for you to learn how to create a list from 1 to n with Python.

Categorized in:

Python,

Last Update: March 15, 2024