[Python] Which is a better way to move an iterator one step forward: `for x in iterator:...

Discussão em 'Python' iniciado por Stack, Junho 4, 2025.

  1. Stack

    Stack Membro Participativo

    While working on a learning task involving overlapping n-wise windows from an input iterable - similar to what itertools.pairwise does - I came across code like this:

    def f(seq):
    it = iter(seq)
    for x in it: break
    for y in it:
    yield x, y
    x = y


    The line for x in it: break was used instead of x = next(it, None) to avoid assigning x at all if seq is empty, which would be the case with the next() call.

    I'm not familiar with CPython internals or low-level details, so I can't say whether this is a justified choice. Could someone help me understand the pros and cons of both approaches for advancing an iterator by one item before a loop?

    Continue reading...

Compartilhe esta Página