all pairs of items in a list without indexing?

Patrick Maupin pmaupin at speakeasy.net
Tue Sep 28 22:48:46 EDT 2004


Steven Bethard <steven.bethard at gmail.com> 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])
 ... 
> Is there any way to do this without indexing

As others have pointed out, you can do this without indexing, but it
may involve overhead of other sorts (list copies, popping, etc.).

I'd just like to point out that, for the problem you are describing
(where you want every possible pair, but order doesn't matter), you
_can_ make your loop perhaps a bit more readable (depending on the
context it is used in), and perhaps a tiny bit faster:

for i in range(1,len(mylist)):
    for j in range(i):
        # do something with (l[i], l[j])

Regards,
Pat



More information about the Python-list mailing list