
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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]
Advertisements