Loop over list of pairs

Alexander Schmolck a.schmolck at gmx.net
Thu Jun 5 16:58:05 EDT 2003


Thomas Güttler <guettler at thomas-guettler.de> writes:

> Hi!
> 
> What is the prefered way of loop over
> a list like this?
>  mylist=[1, "one", 2, "two", 3, "three"]

you could use this:

def xgroup(iter,n=2):
    """
    >>> list(xgroup(range(9), 3))
    [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
    """
    last = []
    for elt in iter:
        last.append(elt)
        if len(last) == n: yield tuple(last); last = []

'as





More information about the Python-list mailing list