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:

  1. Take the value of n in a variable.

    python
    n = 12
  2. Create an empty list to store the generated sequence.

    python
    output = []
  3. Write a For Loop to iterate over the sequence of numbers.

    python
    for i in range(1, n+1):
        output.append(i)
    
  4. Print the list.

    python
    print(output)
    

Complete Program:

python
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:

  1. Take the value of n.

    python
    n = 12
  2. Generate the list using List Comprehension.

    python
    output = [i for i in range(1, n+1)]
  3. Print the list.

    python
    print(output)

Complete Program:

python
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!