Why does this work? (question regarding nested loops)

I was working on this challenge from the Learn Python 3 course. (Challenge ‘5. Exponents’, the last one at the bottom).

I solved it sort of by accident and I don’t understand why it works? The challenge asks to use nested loops to solve it so since I wasn’t too familiar with nested loops, I looked it up on Codecademy’s docs Python section for an explanation.

The explanation made total sense to me but I couldn’t quite see how to apply that info to solving the challenge since it doesn’t really deal with a list within a list but rather two lists inside a function. So there is no nesting, it’s just one level basically…right? The two lists reside side-by-side inside the function (sorry for my very untechnical language :grin:). There is no list inside another list.

So I don’t understand why the solution works:

def exponents(bases, powers):
  answers = []
  for base in bases:
    for power in powers:
      answers.append(base ** power)
  return answers

print(exponents([2, 3, 4], [1, 2, 3]))

According to the explanation I linked to above, the nested loop can only access data residing in the parent loop…and the parent loop in the challenge is just accessing the bases list so how does it ‘know’ the existence of the other list powers and how does it gain access to it?

I hope my confusion is understandable? :confused:

It ‘knows’ about both lists because they are introduced as the iterable in their respective for loops. base and power will be values from their corresponding sequence.

Consider,

for a in (1, 2, 3):
    for b in (1, 2, 3):
        print (a * b)

1
2
3
2
4
6
3
6
9

It still feels a bit strange but I think it’s starting to sink in.
However, I find Codecademy’s explanation of nested loops a bit limited then because based on that alone, I would not have presumed this functionality.
Thanks for the continued help, much appreciated! :wink: :+1:

1 Like