...

/

Nested for Loops

Nested for Loops

Learn about the nested "for" loops in Python, exploring their structure, use cases, and practical examples.

Python lets us easily create loops within loops. 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 in a list 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:

Press + to interact
n = 50
num_list = [10, 25, 4, 23, 6, 18, 27, 47]
for n1 in num_list:
for n2 in num_list: # Now we have two iterators
if(n1 + n2 == n):
print(n1, n2)

In the code above, each element is compared with every other element to check if n1 + n2 is equal to n. This is the power of nested loops. Below slides show the value of each ...

Access this course and 1400+ top-rated courses and projects.