Palindromic Number Pyramid in Python

What You’ll Learn
How to print a palindromic number pyramid in Python, where each row reads the same forward and backward:
1121123211234321123454321
The core idea is to print an increasing sequence, then print the decreasing sequence without repeating the peak.
⭐ Pattern Output
For 5 rows, the pattern looks like this:
1
121
12321
1234321
123454321Complete Python Program
The first inner loop prints ascending numbers, and the second prints descending numbers to form the palindrome.
for i in range(2, 7):
for j in range(1, i):
print(j, end="")
for k in range(i - 2, 0, -1):
print(k, end="")
print()🧠 How It Works
Outer loop controls the height
for i in range(2, 7) generates 5 rows (i = 2..6). Each row prints up to i - 1.
Print ascending part
for j in range(1, i) prints 1 through i - 1.
Print descending part
for k in range(i - 2, 0, -1) prints i - 2 down to 1, completing the palindrome without repeating the peak digit.
New line after each row
print() moves to the next row.
Palindromic rows
Each row has length \(2r-1\). Total digits printed across \(n\) rows is \(1+3+5+\dots+(2n-1)=n^2\), so overall time is O(n²).
Variation — User Input Version
Choose the number of rows at runtime. This keeps the same palindrome idea for any size.
rows = int(input("Enter the number of rows: "))
for i in range(2, rows + 2):
for j in range(1, i):
print(j, end="")
for k in range(i - 2, 0, -1):
print(k, end="")
print()💡 Tips for Enhancement
Try These
- Validate input (reject
rows < 1) before printing - Right-align or center the pyramid using leading spaces
- Add spaces between digits for readability (then update output)
- Replace numbers with letters to create alphabet palindromes
- Build the row as a string for faster printing in large patterns
Avoid
- Repeating the peak digit in the second loop (it breaks the palindrome)
- Forgetting
print()after each row - Mixing default print behavior with
end=""in the same row - Assuming user input is always valid (wrap
int()conversion if needed)
Key Takeaways
Print ascending digits first, then descending digits to form each palindrome row.
Start the descending loop at i - 2 to avoid repeating the peak digit.
Row lengths are odd: 1, 3, 5, ... up to \(2n-1\).
Total digits printed across \(n\) rows is \(n^2\), so runtime is O(n²).
❓ Frequently Asked Questions
i = 2 makes the first row print only 1 (since the ascending loop prints 1..i-1). That cleanly matches the pattern output.rows - r spaces first, then print the palindrome digits.chr(ord('A') + x) or similar. The ascending/descending structure remains the same.Explore More Python Number Patterns!
Keep practicing symmetry and nested loops with more number pattern programs.
Palindromic patterns are a great way to practice thinking in terms of “build left half, then mirror it”—the same idea used in many string and array problems.
12 people found this page helpful
