How can the exponents challenge be done with list comprehension?

is there a way to do this with list comprehension? Thanks

Yes, comprehensions permit nested loops.

>>> def exponents(bases, powers):
    return [b ** x for b in bases for x in powers]

>>> print(exponents([2, 3, 4], [1, 2, 3]))
[2, 4, 8, 3, 9, 27, 4, 16, 64]
>>> 
2 Likes

Ahhhh thank you. I had “new_lst = [base ** power for base in bases AND power in powers]”

“and” instead of “for”

Also, didn’t even occur to me that I didn’t need a variable. Thanks for your help

1 Like

You’re welcome. Now add to the challenge so that the result looks like,

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

Later…

Have you given this any consideration? It might help to know that as we can write a comprehension on two lists (or dictionaries) and use nested loops to yield two values, we can also write a comprension on a comprehension that still yields two variables, but also lets us group the results according to one of the variables.

Just wanted to double-check that I’m understanding correctly. Here is my code for your reference:

def exponents(bases, powers):
  return [[base ** power for power in powers] for base in bases]
  1. Is it generally true that the result of the inner list comprehension [base ** power for power in powers] will be grouped according to the outer list comprehension (in this case, by base)?

  2. Is my understanding of what’s going on here sound?

For each base, a new list is returned where base has been raised to the power of each power in powers.

base = 2, power = 1
[[2]]

base = 2, power = 2
[[2, 4]]

base = 2, power = 3
[[2, 4, 8]]

base = 3, power = 1
[[2, 4, 8], [3]]

and so on…

Without grouping,

>>> def powers(bases, exponents):
    return [a ** x for a in bases for x in exponents]

>>> powers([2, 3, 5, 7],[2, 3, 4, 5])
[4, 8, 16, 32, 9, 27, 81, 243, 25, 125, 625, 3125, 49, 343, 2401, 16807]
>>> 

With grouping,

>>> def exponents(bases, powers):
  return [[base ** power for power in powers] for base in bases]

>>> exponents([2, 3, 5, 7],[2, 3, 4, 5])
[[4, 8, 16, 32], [9, 27, 81, 243], [25, 125, 625, 3125], [49, 343, 2401, 16807]]
>>> 

Man, you’re a god, i find it so beautiful