all pairs of items in a list without indexing?

Steven Bethard steven.bethard at gmail.com
Tue Sep 28 16:34:00 EDT 2004


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, e.g.:

for item1 in ...:
    for item2 in ...:
        # do something with (item1, item2)

I could do something like:

for i, item1 in enumerate(l):
    for j in range(i+1, len(l)):
        (item1, l[j])

but that only gets me halfway there...  I also thought of something like:

for i, item1 in enumerate(l):
    for item2 in l[i+1:]:
        (item1, item2)

but that seems like a lot of wasteful list slicing...

Thanks in advance,

Steve
-- 
You can wordify anything if you just verb it.
        - Bucky Katt, Get Fuzzy



More information about the Python-list mailing list