all pairs of items in a list without indexing?

Duncan Booth duncan.booth at invalid.invalid
Wed Sep 29 04:45:38 EDT 2004


Michael Sparks wrote:

> This is what was asked for:
> 
> # Given a list l which we want all pairs:
>>>> l=[1,2,3,4,5]
>>>> [(l[x],l[y]) for y in xrange(len(l)) for x in xrange(y,len(l)) if
>>>> x!=y] 
> [(2, 1), (3, 1), (4, 1), (5, 1), (3, 2), (4, 2), (5, 2), (4, 3), (5,
> 3), (5, 4)] 

The same thing can be written slightly more succinctly as:

>>> [(l[x],l[y]) for y in xrange(len(l)) for x in xrange(y+1,len(l))]
[(2, 1), (3, 1), (4, 1), (5, 1), (3, 2), (4, 2), (5, 2), (4, 3), (5, 3), 
(5, 4)]




More information about the Python-list mailing list