Home > Software design >  Iterating Over Array Elements in Python
Iterating Over Array Elements in Python

Time:06-13

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...?

CodePudding user response:

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:]):
    ...
  • Related