iterating "by twos"

Daniel da Silva ddasilva at umd.edu
Wed Jul 30 07:08:26 CEST 2008


The following method is similar to the others provided, but yields an
index value as well (similar to the enumerate(iterable) function).
This is useful in some (but not all) situations.

If the iterable object's iterator returns an even number of items then
you're fine; otherwise it will throw away the last item because it
doesn't have a full pair to return.

-------------------------
import itertools

def enumeratePairs(x):
    it = iter(x)

    for i in itertools.count():
        p = it.next()
        q = it.next()
        yield i, (p,q)

    raise StopIteration
--------------------------
>>> for v in enumeratePairs("hello i am daniel"):
...     print v
...
(0, ('h', 'e'))
(1, ('l', 'l'))
(2, ('o', ' '))
(3, ('i', ' '))
(4, ('a', 'm'))
(5, (' ', 'd'))
(6, ('a', 'n'))
(7, ('i', 'e'))
-------------------------------

On Tue, Jul 29, 2008 at 1:36 PM, kj <socyl at 987jk.com.invalid> wrote:
>
>
>
> Is there a special pythonic idiom for iterating over a list (or
> tuple) two elements at a time?
>
> I mean, other than
>
> for i in range(0, len(a), 2):
>    frobnicate(a[i], a[i+1])
>
> ?
>
> I think I once saw something like
>
> for (x, y) in forgotten_expression_using(a):
>    frobnicate(x, y)
>
> Or maybe I just dreamt it!  :)
>
> Thanks!
> --
> NOTE: In my address everything before the first period is backwards;
> and the last period, and everything after it, should be discarded.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list