How Can I Generate a Sequence of Numbers in Python?

Hello Friends Today, through this tutorial, I will tell you How Can I Generate a Sequence of Numbers in Python Program?

There are multiple ways to generate a sequence of numbers in Python:

Using `range()` function:-

# Generate a sequence of numbers from 1 to 10 (inclusive)
numbers = range(1, 11)
# Print the sequence
print(numbers) # Output: range(1, 11)
# Access individual elements using indexing
first_number = numbers[0] # Accesses the first element (1)
last_number = numbers[-1] # Accesses the last element (10)

Explanation:-

1. The `range()` function is the most common and efficient way to generate a sequence of numbers.
2. It takes two optional arguments: `start` (default is 0) and `stop` (exclusive).
3. It creates an immutable sequence object that you can iterate through using a loop or access elements using indexing.

Using list comprehension:-

# Generate a sequence of even numbers from 2 to 20 (inclusive)
even_numbers = [num for num in range(2, 21, 2)]
# Print the sequence
print(even_numbers) # Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Explanation:-

1. List comprehension provides a concise way to create a list based on an existing sequence.
2. The syntax involves iterating over an iterable (here, `range(2, 21, 2)`) and adding elements to the list based on certain conditions (even numbers in this case).

Using a loop:-

# Generate a sequence of squares from 1 to 5
squares = []
for num in range(1, 6):
square = num**2
squares.append(square)
# Print the sequence
print(squares) # Output: [1, 4, 9, 16, 25]

Explanation:-

1. This approach uses a loop to iterate through a desired range and performs calculations on each element.
2. Here, it squares each number and adds the result to the `squares` list.