⚡ TL;DR
Print the snake matrix pattern in Python. Complete working code, expected output, algorithm explanation, and practice variations for beginners learning loops.
The Snake Matrix pattern is a classic loop exercise. Here’s the complete implementation in Python with working code and output.
Pattern to Print
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
21 22 23 24 25Implementation
def snake_matrix(n):
num = 1
for i in range(n):
row = list(range(num, num + n))
if i % 2 == 1: row.reverse()
print(' '.join(f'{x:3d}' for x in row))
num += n
snake_matrix(5)Output
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
21 22 23 24 25How It Works
Fill rows sequentially left-to-right, but reverse every odd row. The result zigzags like a snake.
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
Related Patterns
- Snake Matrix in Dart
- Snake Matrix in Go
- Snake Matrix in Swift
- Checkerboard in Python
- Hollow Cross Plus in Python
- Right-Facing Arrowhead in Python
FAQ
How do you print the Snake Matrix 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 Snake Matrix 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!
