How to loop through all but the last item of a list?


I would like to loop through a list checking each item against the one following it.

Is there a way I can loop through all but the last item using for x in y? I would prefer to do it without using indexes if I can.


freespace answered my actual question, which is why I accepted the answer, but SilentGhost answered the question I should have asked.

Apologies for the confusion.

9/17/2017 10:58:33 PM

Accepted Answer

for x in y[:-1]

If y is a generator, then the above will not work.

9/23/2015 8:47:08 AM

the easiest way to compare the sequence item with the following:

for i, j in zip(a, a[1:]):
     # compare i (the current) to j (the following)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow