2

I need to raise my list [23, 43, 32, 27, 11] to the powers indicated in this list [3, 5, 4, 3, 2].

Meanding the 23 should be raised to the power of 3, 43 to the power of 5 etc...

I can do the whole list to one power with the help of this question: Raising elements of a list to a power but not like how I need.

Should I use two loops? Many thanks for the help.

2 Answers2

7

You could use zip():

>>> a = [23, 43, 32, 27, 11]
>>> b = [3, 5, 4, 3, 2]
>>> c = [x**y for x, y in zip(a, b)]
>>> c
[12167, 147008443, 1048576, 19683, 121]

or map() and operator.pow():

>>> from operator import pow
>>> d = list(map(pow, a, b))
>>> d
[12167, 147008443, 1048576, 19683, 121]
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
1

Use numpy:

import numpy as np

b = np.array([23, 43, 32, 27, 11])
e = np.array([3, 5, 4, 3, 2, 2])

# constrain sizes (like zip)
m = min(b.shape[0], e.shape[0])
b = b[:m]
e = e[:m]

print(b**e)            # 1. typical method
print(np.power(b, e))  # 2. you might like this better in some scenarios
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
  • 4
    Downvoted due to: (i) there is currently no `e` defined (its `p`); and (ii) the solution surely can't work as the arrays are **different lengths**. (and `numpy` is a very heavyweight dependency to answer a simple question) – donkopotamus Jul 02 '18 at 00:29
  • 2
    @donkopotamus `numpy` is the canonical solution for anyone working with numerical data. At the very least, those who have this particular question might consider it. – Mateen Ulhaq Jul 02 '18 at 00:41