for loop question

Paul Hankin paul.hankin at gmail.com
Thu Oct 11 04:12:32 EDT 2007


On Oct 11, 4:40 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Wed, 10 Oct 2007 20:25:00 +0000, Paul Hankin wrote:
> >> A "works-for-me":
>
> >>  >>> 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.
>
> Just for completion, here's another way:
>
> prev = test[0]
> for i in xrange(1, len(test)):
>     print prev, test[i]
>     prev = test[i]

Why not just:

for i in xrange(len(test) - 1):
    print test[i], test[i + 1]

--
Paul Hankin




More information about the Python-list mailing list