Codecademy Forums

FAQ Hint: Be aware of nesting iteratives and loops

Concept

As per this lesson, you may find yourself wanting to combine loops like for and while. However in doing so, it is important to understand how they will interact when nested.

Mechanics

There are a few key issues that I have seen pop up regularly in questions:
The first if you have two for loops, the inner for loop will run completely for each step in the outer for loop. Example:

list1 = [1,2,3]
list2 = ['a', 'b', 'c']
for n in list1:
  for L in list2:
    print(str(n) + L)
#output: 1a, 1b, 1c, 2a, 2b, 2c, 3a, 3b, 3c

As you can see, it cycles through all of the second loop before moving on to #2 in the first loop. This also demonstrates that a variable used in the outer loop can be used in the inner loop. Variables from the inner loop can be used in the outer loop but only after being defined (this could be useful if you were creating a list for example).
On the other hand, an outer while will not be checked during the running of an inner loop.

i = 0
while i < 2:
  for n in range(0,6):
    i = n
    print(i)
#output: 0, 1, 2, 3, 4, 5

As you can see, the inner for loop will run to completion ignoring the while loop even though you may have expected it to stop once i was 2.

These are just a couple examples that will hopefully help solve issues with your own code. Please discuss below and help each other to further solve challenges that arise.

1 Like

@catower, great comments!.

It’s also well to note that (unlike in some other languages) you can’t adjust the value of the iteration variable from within a for loop, as you can from within a while loop.

for i in range(0,3):
    print(i)
    i = i + 10
    print(i)

Output:

0
10
1
11
2
12

Here, at least within the loop, range() keeps an iron grip on the value of i.

4 Likes

Indeed. :+1:

This is because the for implementation in Python leverages an internal counter to track which item from the iterable sequence comes next, and overwrites your target variable (i in your example) with that value each iteration until it reaches the end of the iterator.

This is why you get odd behaviour in some cases, for example if you remove items from a list while iterating over it.

2 Likes