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

Iterating Over Array Elements in Python

Is there a way to improve this code?

list_itr1 = iter(list(df.index))
list_itr2 = iter(list(df.index))
next(list_itr2)
for i in range(len(df.index)-1):
    obj1 = next(list_itr1)
    obj2 = next(list_itr2)

I need to iterate over all elements in a list AND the element right after the current element. This code works but I guess there must be an easy way to this…?

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

>Solution :

Use zip with a slice that skips the first item to get pairs of consecutive elements:

list_itr = list(df.index)
for obj1, obj2 in zip(list_itr, list_itr[1:]):
    ...
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