Nested for Loops

In this lesson, we'll create nested 'for' loops!

Execution of Nested Loops #

Python lets us easily create loops within loops. There’s only one catch: the inner loop will always complete before the outer loop.

For each iteration of the outer loop, the iterator in the inner loop will complete its iterations for the given range, after which the outer loop can move to the next iteration.

Using a Nested for Loop #

Let’s take an example. Suppose we want to print two elements whose sum is equal to a certain number n.

The simplest way would be to compare every element with the rest of the list. A nested for loop is perfect for this:

Get hands-on with 1200+ tech skills courses.