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--) { ... }
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 toimap()to generate consecutive data points. Also, used withizip()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 lambdas):
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
>>> i, j = 0, 10
>>> while i != j:
... # Your code here:
... print "i: %d j: %d" % (i, j)
... i += 1
... j -= 1
...
...
i: 0 j: 10
i: 1 j: 9
i: 2 j: 8
i: 3 j: 7
i: 4 j: 6
If you wonder why it's common to see >>> and ... in code examples it's because people are using the python interpreter (a shell, if you'd like), or a wrapper around the python interpreter like bpython. I really recommend getting bpython for testing code like this.
Depending on the situation you can use zip:
lista = [1,2,3]
listb = [4,5,6]
for x,y in zip(lista, listb)
print(x, y)
outputs:
1 4
2 5
3 6
zip docs are here: http://docs.python.org/3.3/library/functions.html#zip
Also to go with what you were saying two numbers, you could do
for x,y in zip(range(0), range(10, 0, -1))
if x == y:
break
# do stuff
This will give you both increasing and decreasing values.
forin python is for iterating over iterable things, and whilewhiledoes the stuff with variables you'd like C-likeforto do (notice howforin C is just a shortenedwhile, thus quite redundant).