Python - Increasing alternate element pattern in list

This article demonstrates how to create an increasing alternate element pattern in a list where each original element is followed by a string of asterisks that increases in length. We'll use list comprehension with enumerate() to achieve this pattern efficiently.

Understanding the Pattern

The increasing alternate element pattern takes a list like [1, 2, 3] and transforms it to [1, '*', 2, '**', 3, '***']. Each element is followed by asterisks equal to its position (1-indexed).

Using List Comprehension with enumerate()

The enumerate() function adds a counter to each element, starting from 1. We use nested list comprehension to create pairs of (element, asterisks) and flatten them ?

# declare list of integers
my_list = [1, 2, 3]
print("Original list:", my_list)

# Create increasing alternate pattern
response = [value for sub in ((i, "*" * j)
                              for j, i in enumerate(my_list, 1))
            for value in sub]

print("Increasing element pattern:", response)
Original list: [1, 2, 3]
Increasing element pattern: [1, '*', 2, '**', 3, '***']

How It Works

The solution uses a nested list comprehension:

# Breaking down the comprehension
my_list = [1, 2, 3]

# Step 1: enumerate creates (index, value) pairs starting from 1
enumerated = list(enumerate(my_list, 1))
print("Enumerated pairs:", enumerated)

# Step 2: Create tuples of (element, asterisks)
pairs = [(i, "*" * j) for j, i in enumerate(my_list, 1)]
print("Element-asterisk pairs:", pairs)

# Step 3: Flatten the pairs into a single list
result = [value for pair in pairs for value in pair]
print("Final result:", result)
Enumerated pairs: [(1, 1), (2, 2), (3, 3)]
Element-asterisk pairs: [(1, '*'), (2, '**'), (3, '***')]
Final result: [1, '*', 2, '**', 3, '***']

Alternative Approach Using a Simple Loop

For better readability, you can use a simple loop approach ?

def create_increasing_pattern(input_list):
    result = []
    for index, element in enumerate(input_list, 1):
        result.append(element)
        result.append("*" * index)
    return result

# Example usage
numbers = [10, 20, 30, 40]
pattern = create_increasing_pattern(numbers)
print("Input:", numbers)
print("Pattern:", pattern)
Input: [10, 20, 30, 40]
Pattern: [10, '*', 20, '**', 30, '***', 40, '****']

Comparison

Method Readability Performance Best For
List Comprehension Complex Faster Compact one-liners
Simple Loop Clear Good Better understanding

Conclusion

List comprehension with enumerate() provides a concise way to create increasing alternate patterns. While powerful, the simple loop approach offers better readability for complex transformations.

Updated on: 2026-03-25T08:36:01+05:30

207 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements