Python: C for loop with two variables
Question: I'm new to python. Is there a similar way to write this C for loop with 2
variables in python?

    
    
    for (i = 0, j = 20; i != j; i++, j--) { ... }
    


Answer: Python 2.x

    
    
    from itertools import izip, count
    for i, j in izip(count(0, 1), count(20, -1)):
        if i == j: break
        # do stuff
    

Python 3.x:

    
    
    from itertools import count
    for i, j in zip(count(0, 1), count(20, -1)):
        if i == j: break
        # do stuff
    

This uses `itertools.count()`, an iterator that iterates from a certain
starting point indefinitely:

> `itertools.count(start=0, step=1)`
>
> Make an iterator that returns evenly spaced values starting with `n`. Often
> used as an argument to `imap()` to generate consecutive data points. Also,
> used with `izip()` to add sequence numbers.

In Python 2.x you have to use `izip` because Py2K `zip` tries to create a list
of all the results, as opposed to `izip` which returns an `iterator` over the
results as they are obtained. Unfortunately we are dealing with infinite
iterators here so `zip` won't work... this is probably a good point as to why
`zip` has been changed to perform the role of `izip` in Py3K (`izip` no longer
exists there).

If you are crazy about being _functional_ you could even do this (but it looks
ugly in my opinion since I have grown to hate `lambda`s):

    
    
    from itertools import takewhile, izip, count
    for i, j in takewhile(lambda x: x[0] != x[1], izip(count(0, 1), count(20, -1))):
        # do stuff
    

