+4 votes
in Programming Languages by (39.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?



ans= [1,2,4]

1 Answer

+1 vote
by (286k points)

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]