title: Algorithm for itertools.combinations in Python
body: <p>I was solving a programming puzzle involving combinations. It led me to a wonderful <code>itertools.combinations</code> function and I'd like to know how it works under the hood. Documentation says that the algorithm is roughly equivalent to the following:</p>
  
  <pre><code>def combinations(iterable, r):
      # combinations('ABCD', 2) --&gt; AB AC AD BC BD CD
      # combinations(range(4), 3) --&gt; 012 013 023 123
      pool = tuple(iterable)
      n = len(pool)
      if r &gt; n:
          return
      indices = list(range(r))
      yield tuple(pool[i] for i in indices)
      while True:
          for i in reversed(range(r)):
              if indices[i] != i + n - r:
                  break
          else:
              return
          indices[i] += 1
          for j in range(i+1, r):
              indices[j] = indices[j-1] + 1
          yield tuple(pool[i] for i in indices)
  </code></pre>
  
  <p>I got the idea: we start with the most obvious combination (<code>r</code> first consecutive elements). Then we change one (last) item to get each subsequent combination.</p>
  
  <p>The thing I'm struggling with is a conditional inside <code>for</code> loop. </p>
  
  <pre><code>for i in reversed(range(r)):
      if indices[i] != i + n - r:
          break
  </code></pre>
  
  <p>This experession is very terse, and I suspect it's where all the magic happens. Please, give me a hint so I could figure it out.</p>