all pairs of items in a list without indexing?

jepler at unpythonic.net jepler at unpythonic.net
Tue Sep 28 17:57:01 EDT 2004


I think that Steven wants to generate all pairs of items in a list,
not successive pairs.  So for the input
    [1, 2, 3]
he wants
    [[1, 2], [1, 3], [2, 3]]
or some ordering of it, anyway.

I think that I would write
    def all_pairs(seq):
        l = len(seq)
        for i in range(l):
            for j in range(i+1, l):
                yield seq[i], seq[j]
(essentially the OP's first suggestion, but with 'len(seq)' prematurely
optimized out) Something about taking a slice of seq for the inner loop
doesn't seem right to me.

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/8e077abd/attachment.sig>


More information about the Python-list mailing list