Nested Loops


In an exercise I was working on, I wanted to raise a list of bases to a list of powers and return the result. I tried a complicated method with list comprehensions and regular for loops, but nested loops make this so much easier:

def exponents(bases, powers):

  lst = []

  for base in bases:
      for power in powers:
        lst.append(base ** power)

  return lst

exponents([2, 3, 4], [1, 2, 3]) returns:

[2, 4, 8, 3, 9, 27, 4, 16, 64]

Leave a Reply