Create a List with n Elements from 1 to n in Python



Suppose we have a number n. We have to create a list of elements of size n, the elements are from 1 to n.

So, if the input is like n = 5, then the output will be [1,2,3,4,5]

To solve this, we will follow these steps −

  • use python list comprehension strategy to solve this problem
  • create a list with i for each i from 1 to n, for this we use range() function. This will take lower bound which is n here, and upper bound n+1 because we want to generate up to n.

Example

Let us see the following implementation to get better understanding −

def solve(n):
   return [i for i in range(1,n+1)]
n = 5
print(solve(n))

Input

5

Output

[1, 2, 3, 4, 5]
Updated on: 2021-10-12T07:14:45+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements