for loop question

Paul Rubin http
Thu Oct 11 04:24:50 EDT 2007


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
> >>  >>> pairs = (test[i:i+2] for i in xrange(len(test)-1))
> >>  >>> for a,b in pairs:
> >>  ...     print a,b
> > 
> > for a, b in zip(test, test[1:]):
> >   print a, b
> 
> May be unfortunately slow if test is half a gigabyte of data, what with 
> essentially making three copies of it. Lazy procedures like the generator 
> expression above are often much better.

Untested:

    from itertools import izip, islice
    for a,b in izip(test, islice(test,1,None)):
       print a,b

seems more natural.



More information about the Python-list mailing list