pairs from a list

Alan Isaac aisaac at american.edu
Tue Jan 22 08:19:04 EST 2008


I suppose my question should have been,
is there an obviously faster way?
Anyway, of the four ways below, the
first is substantially fastest.  Is
there an obvious reason why?

Thanks,
Alan Isaac

PS My understanding is that the behavior
of the last is implementation dependent
and not guaranteed.

def pairs1(x):
    for x12 in izip(islice(x,0,None,2),islice(x,1,None,2)):
        yield x12

def pairs2(x):
    xiter = iter(x)
    while True:
        yield xiter.next(), xiter.next()

def pairs3(x):
    for i in range( len(x)//2 ):
        yield x[2*i], x[2*i+1],

def pairs4(x):
    xiter = iter(x)
    for x12 in izip(xiter,xiter):
        yield x12



More information about the Python-list mailing list