Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to create a list with n elements from 1 to n in Python
Creating a list with n elements from 1 to n is a common task in Python. There are several efficient approaches using list comprehension, range() with list(), and other methods.
So, if the input is like n = 5, then the output will be [1, 2, 3, 4, 5]
Using List Comprehension
List comprehension provides a concise way to create lists by iterating over a range ?
def solve(n):
return [i for i in range(1, n+1)]
n = 5
result = solve(n)
print(result)
[1, 2, 3, 4, 5]
Using range() with list()
Convert the range object directly to a list for a simpler approach ?
def create_list(n):
return list(range(1, n+1))
n = 5
result = create_list(n)
print(result)
[1, 2, 3, 4, 5]
Using a for Loop
Traditional approach using a for loop to append elements ?
def create_list_loop(n):
numbers = []
for i in range(1, n+1):
numbers.append(i)
return numbers
n = 5
result = create_list_loop(n)
print(result)
[1, 2, 3, 4, 5]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Fast | Pythonic style |
list(range()) |
Very High | Fastest | Simple sequences |
| For Loop | Medium | Slower | Complex operations |
Conclusion
Use list(range(1, n+1)) for the most readable and efficient solution. List comprehension is ideal when you need to apply transformations during list creation.
Advertisements
