Create a list of numbers from 1 to n
What You'll Learn: In this tutorial, you'll discover how to create a list of numbers from 1 to n using Python. This is like making a sequence of numbers, perfect for counting or organizing items!
Method 1: Using a For Loop
You can create a list of numbers from 1 to n using a For Loop along with the range() function. Here's how you can do it:
Steps:
Take the value of
nin a variable.pythonn = 12Create an empty list to store the generated sequence.
pythonoutput = []Write a For Loop to iterate over the sequence of numbers.
pythonfor i in range(1, n+1): output.append(i)Print the list.
pythonprint(output)
Complete Program:
n = 12
output = []
for i in range(1, n+1):
output.append(i)
print(output)
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Method 2: Using List Comprehension
A more concise way to create a list of numbers from 1 to n is by using List Comprehension. This method is shorter and often preferred for its readability.
Steps:
Take the value of
n.pythonn = 12Generate the list using List Comprehension.
pythonoutput = [i for i in range(1, n+1)]Print the list.
pythonprint(output)
Complete Program:
n = 12
output = [i for i in range(1, n+1)]
print(output)
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Summary:
In this Python tutorial, we learned how to create a list of numbers from 1 to n using two methods: a For Loop with range() and List Comprehension. Both methods allow you to generate sequences easily and are useful for various applications. Keep experimenting and have fun with lists in Python!