+4 votes
in Programming Languages by (40.5k points)
Which Python function should I use to compute 2^p for all p in an array, where p is an element of the array?

E.g.

a=[0,1,2]

ans= [1,2,4]

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

You can use Numpy's exp2() function. It calculates 2**k for all k in the input array.

Here is an example:

>>> import numpy as np
>>> a=[0,1,2]
>>> np.exp2(a)
array([1., 2., 4.])
 

Another approach:

>>> [2**k for k in a]
[1, 2, 4]


...