Loops code challenge - number 6 help on nested loops

Hi all,

I have a question about what this code does exactly. It is the solution to code challenge 6 on loops:


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


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

I am confused about the nested loop that is happening here. Generally, as far as I am aware, the first for loop will refer to the group of numbers 2,3,4 for the first iteration and then 1,2,3 for the second iteration. If we do a nested loop (another loop within this loop), the code will be doing something with the individual numbers: 2,3,4,1,2,3. Isn’t this intuition generally correct? This is what I got from the nested loops section.

In the example above(code challenge), I do not follow how the nested loop works and how / where the first group of numbers (2,3,4) are assigned to base and the other numbers assigned power.

Thanks
Takis

Hi @tagrunner29698,

In the first iteration of the outer loop, base has the value 2. During that iteration, the inner loop iterates through all the values in powers, namely 1, 2, and 3.

In the second iteration of the outer loop, base has the value 3. During that iteration, the inner loop again iterates through all the values in powers, which are 1, 2, and 3.

In the third iteration of the outer loop, base has the value 4, and the inner loop again iterates through all the values in powers.

1 Like