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 while
and for
loops. In this article we focus specifically on nested for
loops.
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.
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?
Why is this the output? Well:
- for the first iteration,
i = 0
so for the inner loop we havefor j in range(0)
which doesn’t get executed. - Next
i = 1
and we havefor j in range(1)
, giving only1 0
. - Finally
i = 2
and we havefor j in range(2)
, giving2 0
and2 1
stopping beforej = 2
becauserange
does 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
end=""
as inprint(i, end="")
. - 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.
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.
Good luck!
2 Comments on “Python Nested FOR Loops”