all pairs of items in a list without indexing?

jepler at unpythonic.net jepler at unpythonic.net
Wed Sep 29 00:00:43 CEST 2004


On Tue, Sep 28, 2004 at 09:47:32PM +0000, Jim Sizelove wrote:
> Steven Bethard wrote:
> >So I need to do something like:
> >
> >for i in range(len(l)):
> >    for j in range(i+1, len(l)):
> >        # do something with (l[i], l[j])
> >
> >where I get all pairs of items in a list (where I'm thinking of pairs
> >as sets, not tuples, so order doesn't matter).  There isn't really
> >anything wrong with the solution here, but since Python's for-each
> >construction is so nice, I usually try to avoid range(len(..)) type
> >calls and list indexing when I can...  Is there any way to do this
> >without indexing
> 
> Are you trying to pair each item in a list with every other
> item exactly once?  Maybe this code does what you want:

> 
> while len(L)>0:
>     item1 = L.pop()
>     for item2 in L:
>         print (item1, item2)

This looks good, as long as the fact that the "item1"s will come
out of the list backwards is OK.  

I'd write 'while L:' instead of your more complicated test, though.

    def all_pairs(L):
        while L:
            i = L.pop()
            for j in L: yield i, j

>>> list(all_pairs(range(5)))
[(4, 0), (4, 1), (4, 2), (4, 3), (3, 0), (3, 1), (3, 2), (2, 0), (2, 1), (1, 0)]

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040928/5f2fd269/attachment.pgp>


More information about the Python-list mailing list