for loop question

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Oct 10 23:40:19 EDT 2007


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]



-- 
Steven.



More information about the Python-list mailing list