+3 votes
in Programming Languages by (56.8k points)
How can I find the reciprocal of all elements of a list in Python? Instead of using for loop, I want to know if there is any function for it?

1 Answer

+2 votes
by (74.2k points)
selected by
 
Best answer

The reciprocal() function of NumPy can be used for it. It returns the reciprocal of the argument, element-wise. If the elements are integer, you need to change them to float.

Here is an example.

>>> import numpy as np
>>> a=np.array([2,3,4,5,6])
>>> a
array([2, 3, 4, 5, 6])
>>> np.reciprocal(a.astype(float))
array([0.5       , 0.33333333, 0.25      , 0.2       , 0.16666667])
 


...