all pairs of items in a list without indexing?

Alex Martelli aleaxit at yahoo.com
Wed Sep 29 15:50:47 CEST 2004


Steven Bethard <steven.bethard at gmail.com> wrote:

> <jepler <at> unpythonic.net> writes:
> >     def all_pairs(L):
> >         while L:
> >             i = L.pop()
> >             for j in L: yield i, j
> 
> Interesting.  I hadn't thought of this one -- it's not bad other than
> requiring the list copy (since I need to maintain the original list).

If you start with an L=list(L), you can also optionally L.reverse() to
play with the ordering (if significant, issue still not clarified).

Ordering apart, performance is still not quite as good as with the
slicing you consider wasteful, in my measurements.  Remember with the
slicing we got about 1.42e+05 microseconds -- with this approach we see:

kallisti:~/cb alex$ python2.4 timeit.py -s'l=range(333)' -s'
def alp(L):
  L = list(L)
  while L:
    it1 = L.pop()
    for it2 in L: yield it1, it2
' 'list(alp(l))'
10 loops, best of 3: 1.51e+05 usec per loop


Alex



More information about the Python-list mailing list