Why do I Need Nested Loops in Python?
Nested loops are a very important concept in Python programming and Computer Science, are used in many algorithms. For example sorting algorithms such as Bubble Sort and Selection Sort rely on them, as does iterating through a 2D list. Sometimes
while loops are used or a combination of
for loops. In this article we focus specifically on nested
Python Nested For Loops Example 1
Type the following code into your favourite Python editor:
for i in range(2): for j in range(2): print(i, j)
What will the output be? Take a moment to think about it and write down your answer before running the code and checking.
0 0 0 1 1 0 1 1
Did you get it right? See the video for an explanation.
Python Nested For Loops Example 2
Next we introduce an important concept: using the outer loop counter to control the range of the inner loop. See the example below.
for i in range(3): for j in range(i): # Using the outer loop counter in the inner loop range print(i, j)
What will the output be?
0 0 1 0 2 0 2 1
Why is this the output? Well:
- for the first iteration,
i = 0so for the inner loop we have
for j in range(0)which doesn’t get executed.
i = 1and we have
for j in range(1), giving only
i = 2and we have
for j in range(2), giving
2 1stopping before
j = 2because
rangedoes that – as you should be getting used to by now.
Python Nested For Loops Example 3
Take a look at this pattern:
1 12 123 1234 12345 123456 1234567 12345678 123456789
Can you use you new found skill with nested
for loops to get Python to produce it for you?
A couple of tips:
- To get Python not to add a new line after every print statement, add
- To force the output onto a new line just use
print()with no argument.
Have a good go at this before looking at the solution below.
for i in range(1, n + 1): for j in range(1, i + 1): print(j, end="") print()
So there it is – you should now be more comfortable and confident with nested for loops in Python. Learning to control iteration like this is going to make you a stronger programmer and help you succeed in you GCSE or A Level Computer Science exam.