How to write a loop for two variables at a time from a list in a more clean code

I have a list of values and I want to get them by pairs and perform an operation with this pair… Any operation. Can be subtraction, since I am more interested in knowing the best way to get the variables by pairs for this loop.

vals = [1, 3, 3, 6, 8, 12]

And I want to perform operations in pairs:
3-1 , 3-3, 6-3, 8-6, 12-8

And I wrote this code:

for i in range( len(vals)-1 ):
  j = i+1
  val1, val2 = vals[i], vals[j]
  r = val2 - val1
  print(r)

It returns 2, 0, 3, 2, 4.

Is there a way to write this operation with a cleaner code?

>Solution :

One option is to use zip to combine each item with the following one in a single iterable, which lets you do something like:

>>> vals = [1, 3, 3, 6, 8, 12]
>>> print(*(j - i for i, j in zip(vals, vals[1:])))
2 0 3 2 4

Leave a Reply