How to generate sequences in Python?

A sequence is a positionally ordered collection of items, where each item can be accessed using its index number. The first element's index starts at 0. We use square brackets [] with the desired index to access an element in a sequence. If the sequence contains n items, the last item is accessed using the index n-1.

In Python, there are built-in sequence types such as lists, strings, tuples, ranges, and bytes. These sequence types are classified into mutable and immutable. The mutable sequence types are those whose data can be changed after creation, such as list and byte arrays. The immutable sequence types are those data that cannot be changed such as tuples, strings, range, and bytes.

Based on the data type of the elements, sequences are classified into two types −

  • Homogeneous: In this sequence, all elements have the same data type
  • Heterogeneous: This sequence can store elements of different data types such as integers, strings, objects, etc.

Various Techniques to Generate Sequences

Following are the various techniques to generate sequences in Python −

Using Loop to Generate Sequence

We can generate a sequence using a loop by starting with an empty sequence and appending values that meet a specified condition.

Example

In the following example, we have generated a sequence of all even numbers below 20 using the for loop

my_list = []
for i in range(0, 20):
    if i % 2 == 0:
        my_list.append(i)
print(my_list)

Following is the output of the above code −

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Using List Comprehension

We can generate sequences using list comprehension. This technique allows us to create a list efficiently by combining a for loop and optional conditional statements in a single line of code. List comprehensions can be used to generate a new list or transform an existing one.

Example

Here, we have generated a list of cubes for each element in the tuple_1 using list comprehension −

tuple_1 = (2, 4, 6, 8)
list_comp = [i**3 for i in tuple_1]
print("List comprehension:", list_comp)

Following is the output of the above code −

List comprehension: [8, 64, 216, 512]

Example with Condition

We can also add conditions to list comprehension to filter elements −

numbers = range(1, 11)
even_squares = [x**2 for x in numbers if x % 2 == 0]
print("Even squares:", even_squares)

Following is the output of the above code −

Even squares: [4, 16, 36, 64, 100]

Using Generator Comprehension

Generator comprehension is similar to list comprehension but returns a generator object instead of a list. To generate an object using a generator function, we use the yield keyword instead of the return keyword. This generator function returns a sequence lazily, consuming less memory.

Example with Generator Function

The following example demonstrates generating a sequence using generator comprehension −

def power_sequence(n):
    for i in range(n):
        yield i**2
        
result_1 = list(power_sequence(4))
print("Generator Function:", result_1)

Following is the output of the above code −

Generator Function: [0, 1, 4, 9]

Example with Generator Expression

Generator expressions use parentheses instead of square brackets −

# Generator expression
gen_expr = (x**2 for x in range(5))
print("Generator expression:", list(gen_expr))

# Memory efficient for large sequences
squares_gen = (x**2 for x in range(1000000))
print("First 5 squares:", [next(squares_gen) for _ in range(5)])

Following is the output of the above code −

Generator expression: [0, 1, 4, 9, 16]
First 5 squares: [0, 1, 4, 9, 16]

Using range() to Generate Sequence

In Python, range() is an in-built function that returns a sequence of numbers, starting from 0 by default, increments by 1 (by default), and stops before a specified number.

Following is the syntax of the range() function −

range(start, stop, step)

Example

Here, we have generated two sequences: my_sequence1 and my_sequence2. The first sequence contains numbers from 0 to 9, and the second contains numbers from 0 to 9 with a step of 2 −

# Generate numbers from 0 to 9
my_sequence1 = range(10)
print("Generated sequence from 0 to 9:")
print(list(my_sequence1)) 

# Generate numbers with a step of 2
my_sequence2 = range(0, 10, 2)
print("Generated numbers with a step of 2:")
print(list(my_sequence2))

Following is the output of the above code −

Generated sequence from 0 to 9:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Generated numbers with a step of 2:
[0, 2, 4, 6, 8]

Example with Negative Step

We can also generate sequences in reverse order using negative step values −

# Generate numbers in reverse order
reverse_seq = range(10, 0, -1)
print("Reverse sequence:", list(reverse_seq))

# Generate even numbers in reverse
even_reverse = range(20, 0, -2)
print("Even numbers in reverse:", list(even_reverse))

Following is the output of the above code −

Reverse sequence: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even numbers in reverse: [20, 18, 16, 14, 12, 10, 8, 6, 4, 2]

Comparison of Methods

Method Memory Usage Performance Best For
Loops Creates full list Slower Complex logic
List Comprehension Creates full list Fast Simple transformations
Generator Lazy evaluation Memory efficient Large sequences
range() No memory for values Very fast Numeric sequences

Conclusion

Python offers multiple ways to generate sequences efficiently. Use range() for numeric sequences, list comprehension for transformations, and generators for memory-efficient processing of large datasets.

Updated on: 2026-03-24T20:40:14+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements