Search code examples
pythonenvironment-variablespython-itertoolsscopes

python itertools combinations logic


I'm looking at the code for the combinations on the python documentation for itertools (https://docs.python.org/2/library/itertools.html)

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = 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)

On the line where it says indices[i] += 1, why is it able to find 'i' ? As far as I understand once you are out of the for loop (which starts right after while True), variable 'i' should not exist (just like the i mentioned in the first yield sentence) !!!

Also can someone explain the logic in english ? I understand until the first yield but then I'm lost. Thanks in advance.


Solution

  • Python is not block scoped. Roughly speaking, Python is function scoped. In other languages, if you did

    for (int i = 0; i < whatever; i++) {
        ...
    }
    

    then i would be local to the for loop. In Python, the equivalent

    for i in xrange(whatever):
    

    uses an i variable local to the entire enclosing function. Also, i never takes the value whatever, so when the loop ends, we still have i == whatever - 1.