all pairs of items in a list without indexing?

Michael Sparks zathras at thwackety.com
Tue Sep 28 19:05:43 EDT 2004


On Tue, 28 Sep 2004 jepler at unpythonic.net wrote:

> I think that Steven wants to generate all pairs of items in a list,
> not successive pairs.

Sorry, you're right, I misread. That'll teach me for reading and posting
when it's late and I'm tired :)

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)]

ie just ask for it. Since this works on indices, you still get the same
pairs even when all the values in l are the same:

>>> l=[1,1,1,1,1]
>>> [(l[x],l[y]) for y in xrange(len(l)) for x in xrange(y,len(l)) if x!=y]
[(1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1)]

At least I think this is what's wanted this time* :) Bit wasteful though
due to the list creation.
   * Depends on whether Steven wants items paired with themselves or not.
     If he does ditching the if x!=y term would be what is wanted.

Regards,


Michael






More information about the Python-list mailing list