1

I was really surprised that I couldn't find this anywhere. In most languages, going through all possible pairs in a list looks something like this:

for (i = 0; i < length; i++) 
    for (j = i + 1; j < length; j++)
         do stuff

But in python, you would have to do:

for i in range (len(clusters)):
    for j in range (i+1, len(clusters)):
        do stuff

I feel like that isn't very pythonic. What's the best way to do this?

Cras
  • 157
  • 8
  • I'd do it this way: `[(i,j) for i in xrange(1,len(mylist)) for j in xrange(i,len(mylist))]` You could also call some function `foo(i,j)` of course. – Sadık Oct 26 '17 at 15:41

1 Answers1

4

You can use combinations():

from itertools import combinations
combinations('ABCD', 2) --> AB AC AD BC BD CD

Python discourages "C-style" loops, because you actually hardly need them if you adapt to it. You can do it quite easily using emumerate() to still get the index, and some slicing, using pure python:

lst = 'ABCD'
for index, first in enumerate(lst):
    for second in lst[index+1:]:
        print(first, second)
Felk
  • 7,720
  • 2
  • 35
  • 65