Python Program to Print Number Pattern
for loops; for example, for i in range(1, n+1): print(*range(1, i+1)) prints numbers from 1 up to the current line number.Examples
How to Think About It
Algorithm
Code
n = 5 for i in range(1, n + 1): for j in range(1, i + 1): print(j, end=' ') print()
Dry Run
Let's trace the program for n = 3 to see how it prints the pattern.
Start outer loop with i=1
Print numbers from 1 to 1: prints '1 '
Move to next line
Print newline
Outer loop i=2
Print numbers from 1 to 2: prints '1 2 '
Move to next line
Print newline
Outer loop i=3
Print numbers from 1 to 3: prints '1 2 3 '
Move to next line
Print newline and end
| i | Printed Numbers |
|---|---|
| 1 | 1 |
| 2 | 1 2 |
| 3 | 1 2 3 |
Why This Works
Step 1: Outer loop controls lines
The outer for loop runs from 1 to n, deciding how many lines to print.
Step 2: Inner loop prints numbers
The inner for loop prints numbers from 1 up to the current line number.
Step 3: Print newline after each line
After printing each line's numbers, print() moves the cursor to the next line.
Alternative Approaches
n = 5 for i in range(1, n + 1): print(' '.join(str(x) for x in range(1, i + 1)))
n = 5 for i in range(1, n + 1): print(*[j for j in range(1, i + 1)])
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops: the outer loop runs n times, and the inner loop runs up to n times in the last iteration, resulting in O(n^2) time.
Space Complexity
The program uses constant extra space, only variables for counters, so space complexity is O(1).
Which Approach is Fastest?
All approaches have similar time complexity; using string join or unpacking can make code cleaner but does not improve time complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested loops with print | O(n^2) | O(1) | Simple and clear for beginners |
| String join with range | O(n^2) | O(1) | Cleaner code, easier to read |
| List comprehension with unpacking | O(n^2) | O(1) | Concise and pythonic |