Question

This is a really basic syntax question that I just don't know how to do/can't figure out how to look for an explanation of. Basically, you can really easy compare/compute things between successive terms of an iterable with, say, this:

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

but it seems like there definitely ought to be a way to do that without messing about with the range(len()) thing? like, i ought to be able to have

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

except that "nextitem" would be some sort of keyword or a slice syntax or...I don't really know what it would be, I just feel like it has to exist. i thought for item, nextitem in iterable might work but that only seems to refer to tuples INSIDE the iterable. What am I looking for here?

Was it helpful?

Solution

There's not a built in way to do it, but this works:

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

izip_longest docs

depending on what your iterable actually is, you could do zip(iterable[:-1], iterable[1:])

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top