⚡ TL;DR
Print the alternating number triangle pattern in Python. Complete working code, expected output, and a clear step-by-step explanation for beginners learning loops.
The Alternating Number Triangle pattern is a classic loop exercise. Here’s the complete implementation in Python with working code and output.
Pattern to Print
1
12
121
1212
12121Implementation
def alternating_number(n):
for i in range(1, n + 1):
print("".join("1" if j % 2 == 0 else "2" for j in range(i)))
alternating_number(5)Output
1
12
121
1212
12121How It Works
Within each row, positions alternate between 1 and 2 based on whether the column index is even or odd. The modulo operator (j % 2) drives the alternation.
Practice Variations
- Try printing the pattern with a different character (e.g.,
#or+) - Modify the code to accept the pattern size as user input
- Combine this pattern with its inverse to create a more complex shape
Complexity
- Time: O(n²) — the grid or line count grows quadratically
- Space: O(1) — only loop counters are needed
FAQ
How do you print the Alternating Number Triangle pattern in Python?
Use nested loops: the outer loop walks through the rows while the inner loop prints the characters or values for each row. The complete Python implementation with expected output is shown in the sections above.
What is the time complexity of the Alternating Number Triangle pattern in Python?
The time complexity is O(n²) and the space complexity is O(1), since the pattern is built with a fixed number of loop counters and printed row by row.
Happy coding!

Written by Mihir Pipermitwala
Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.
More about Mihir →