List numbering in Python

  1. HowTo
  2. Python How-To's
  3. List of Numbers From 1 to N in Python

List of Numbers From 1 to N in Python

Python Python List

Created: March-27, 2021 | Updated: July-18, 2021

This tutorial will discuss how to create a list of numbers from 1 to some specified number.

Create a User-Defined 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.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python List

  • Find All the Indices of an Element in a List in Python
  • Convert a List to String in Python
    • Get Class Name in Python
    • Sort With Lambda in Python
    report this ad

    Video liên quan

    Chủ Đề