Raising elements of a list to powers indicated in another list

Multi tool use
Multi tool use


Raising elements of a list to powers indicated in another list



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.





[ x**y for x,y in zip([23,43,32,27,11],[3, 5, 4, 3, 2, 2]) ]
– Amit Singh
Jul 2 at 0:09



[ x**y for x,y in zip([23,43,32,27,11],[3, 5, 4, 3, 2, 2]) ]





Yes there was a extra 2 in the 2nd list
– Chloé Moreau
Jul 2 at 0:34




2 Answers
2



You could use zip():


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():


map()


operator.pow()


>>> from operator import pow
>>> d = list(map(pow, a, b))
>>> d
[12167, 147008443, 1048576, 19683, 121]





Any chance I can convince you to reverse the order of those two suggestions (zip above map)?
– jedwards
Jul 2 at 0:12



zip


map





Sure will do that.
– shash678
Jul 2 at 0:13





It worked much appreciated.
– Chloé Moreau
Jul 2 at 0:36



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





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 2 at 0:29



e


p


numpy





@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 2 at 0:41


numpy






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

LCxx vIpKnazdRuPHX1hOP E,ng
0ilB0Nape MunKg1z1wOPOTVzQVykxuneCdJ04Nr7d5c

Popular posts from this blog

Rothschild family

Cinema of Italy