Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading