See Adjacent Python Iteration Term While in a For Loop

This is really a basic syntax question, which I just don’t know how to do / cannot understand how to look for explanations. Basically, you can very easily compare / calculate things between consecutive terms of iteration, for example:

for i in range(len(iterable)):
    if iterable[i] == iterable[i + 1]:
        do whatever

but it seems that there definitely should be a way to do this without delving into the range problem (len ())? for example i have to have

for item in iterable:
    if item == nextitem:
        do whatever

except that "nextitem" will be some kind of keyword or slice syntax or ... I don’t know what it will be, I just feel that it should exist. I thought it for item, nextitem in iterablemight work, but this seems to only apply to INSIDE iterable tuples. What am I looking for here?

+4
1

, :

from itertools import izip_longest
for item, nextitem in izip_longest(iterable, iterable[1:]):
    if item == nextitem:
        do whatever better

izip_longest docs

, , zip(iterable[:-1], iterable[1:])

+5

All Articles