Q:

How can I apply a function to pairs of elements in a list with Python?

I have a list of numbers and I want to find the difference of the elements in it as a percentage. Currently I am using a for loop. Is there another way, maybe using numpy ?
example_list = [1., 5., 4., 2., 10., 8., 3., 1.]
percentage_difference = []
for index, i in enumerate(example_list):
    if index + 1 < len(example_list):
        previous = example_list[index + 1]
        difference = round((previous - i) / previous , 3)
        percentage_difference.append(difference)

output explanation: (5 - 1) / 1

A:

You can use numpy.diff for this:
In [13]: import numpy as np

In [14]: a = np.array([1., 5., 4., 2., 10., 8., 3., 1.])                                         

In [15]: np.diff(a)/a[1:]                                                                        
Out[15]: 
array([ 0.8       , -0.25      , -1.        ,  0.8       , -0.25      ,                          
       -1.66666667, -2.        ])      

In [16]: np.round(np.diff(a)/a[1:], 3)
Out[16]: array([ 0.8  , -0.25 , -1.   ,  0.8  , -0.25 , -1.667, -2.   ])

In pure Python you can do this using zip with either use map or a list comprehension. Here's an example using map:
>>> def calculate(x_y):
    x, y = x_y
    return round((x-y)/x, 3)

>>> map(calculate, zip(lis[1:], lis[:-1]))
[0.8, -0.25, -1.0, 0.8, -0.25, -1.667, -2.0]

