all pairs of items in a list without indexing?

Jim Sizelove sizelji at insightbb.com
Tue Sep 28 17:47:32 EDT 2004


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)

pop() removes one item from the list.  The inner for loop matches that 
item with each of the remaining items.  At the end of the outer loop the 
list L is empty; you may want to run this loop over a copy of the list 
if you want to do other things with the list later.

HTH,

Jim



More information about the Python-list mailing list