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

Question

Asked By – David Sykes

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.

Note

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.

Now we will see solution for issue: How to loop through all but the last item of a list?


Answer

for x in y[:-1]

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

This question is answered By – freespace

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0