all pairs of items in a list without indexing?
Marc Christiansen
tolot at jupiter.solar-empire.de
Tue Sep 28 18:31:50 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])
>
[...]
> 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...
You could try something like:
for i, item1 in enumerate(l):
for item2 in itertools.islice(l, i+1, None):
(item1, item2)
I'm not sure which version I prefer.
Marc
More information about the Python-list
mailing list