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 ). 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?