Palindromic Number Pyramid in Python

What You’ll Learn
How to print a palindromic number pyramid in Python. Each row prints increasing numbers from 1 to the row index, then decreasing back to 1.
You’ll also learn how leading spaces are used to center-align the pyramid.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1Complete Python Program
Print spaces first, then print ascending numbers up to i, and finally print descending numbers back to 1.
rows = 5
for i in range(1, rows + 1):
for _ in range(rows, i, -1):
print(" ", end=" ")
for k in range(1, rows + 1):
if k <= i:
print(k, end=" ")
for m in range(i - 1, 0, -1):
print(m, end=" ")
print()🧠 How It Works
Set the pyramid height
rows = 5 sets how many rows the pyramid will have.
Print leading spaces
The first loop prints spaces so the numbers shift left as i increases, giving a centered pyramid.
Ascending sequence (1..i)
The second loop prints numbers from 1 up to the current row limit i.
Descending sequence (i-1..1)
The third loop prints i-1 down to 1 to mirror the left side and form a palindrome.
Symmetric pyramid
Each row prints \(2i-1\) numbers, so total output is \(O(r^2)\) for r rows.
Variation — User Input Version
Let the user choose how many rows to print.
rows = int(input("Enter number of rows: "))
if rows < 1:
raise ValueError("rows must be at least 1")
for i in range(1, rows + 1):
for _ in range(rows, i, -1):
print(" ", end=" ")
for k in range(1, rows + 1):
if k <= i:
print(k, end=" ")
for m in range(i - 1, 0, -1):
print(m, end=" ")
print()💡 Tips for Enhancement
Try These
- Use a fixed-width cell for better alignment with multi-digit numbers
- Print without spaces for a compact pyramid
- Build each row in a list and join it to avoid trailing spaces
- Invert the pyramid by printing rows in reverse order
- Replace numbers with letters for an alphabet palindrome pyramid
Avoid
- Forgetting the descending loop (the row won’t be palindromic)
- Printing incorrect spaces (the pyramid won’t align)
- Mixing 0-based and 1-based ranges in the loop boundaries
- Using
rows < 1without validation
Key Takeaways
Leading spaces align the pyramid to the center.
Each row prints 1..i then i-1..1.
Each row contains 2i-1 numbers.
Total printed values grow as O(r²).
❓ Frequently Asked Questions
i-1 down to 1 mirrors the ascending part without repeating the peak value i, making the row palindromic.i prints i ascending numbers and i-1 descending numbers, so it prints 2i-1 numbers in total.Explore More Python Number Patterns!
Palindrome pyramids are a fun way to practice symmetry and loop boundaries.
These rows use an odd count of numbers: 1, 3, 5, 7… and the sum of the first \(r\) odd numbers is \(r^2\).
7 people found this page helpful
