List numbering in Python
List of Numbers From 1 to N in PythonPython Python List Created: March-27, 2021 | Updated: July-18, 2021 Show 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 NThis 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. 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 NThe 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: 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: Use the numpy.arange() to Create a List of Numbers From 1 to NThe 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
|