Into itertools

Arnaud Delobelle arnodel at googlemail.com
Mon Apr 27 10:50:42 CEST 2009


On 26 Apr, 17:32, bearophileH... at lycos.com wrote:
> Some idioms are so common that I think they deserve to be written in C
> into the itertools module.
>
> 1) leniter(iterator)
[...]
> A Python implementation:
>
> def leniter(iterator):
>     if hasattr(iterator, "__len__"):
>         return len(iterator)
>     nelements = 0
>     for _ in iterator:
>         nelements += 1
>     return nelements

Some people would write it as:

def leniter(iterable):
    if hasattr(iterable, '__len__'):
        return len(iteratble)
    return sum(1 for _ in iterable)

[...]

> 2) xpairwise(iterable)
>
> This is at the the bottom of the itertools docs:
>
> def pairwise(iterable):
>     a, b = tee(iterable)
>     for elem in b:
>         break
>     return izip(a, b)
>
> The following of mine is faster:
>
> def xpairwise(iterable):
>     return izip(iterable, islice(iterable, 1, None))

This doesn't work if the iterable is an iterator.

E.g

>>> it = iter(range(5))
>>> list(xpairwise(it))
[(0, 2), (3, 4)]

[...]
> 3) xpairs(seq)
>
> This is a Python implementation:
>
> def xpairs(seq):
>     len_seq = len(seq)
>     for i, e1 in enumerate(seq):
>         for j in xrange(i+1, len_seq):
>             yield e1, seq[j]
>

Why not:

def xpairs(seq):
    for i, el in enumerate(seq):
        for j in xrange(i):
            yield seq[j], el


--
Arnaud



More information about the Python-list mailing list