Loops and things

Gary Herron gherron at islandtraining.com
Fri Dec 14 10:52:12 EST 2007


rocco.rossi at gmail.com wrote:
> I was wondering how and if it's possible to write a loop in python
> which updates two or more variables at a time. For instance, something
> like this in C:
>
> for (i = 0, j = 10; i < 10 && j < 20; i++, j++) {
>     printf("i = %d, j = %d\n", i, j);
> }
>
> So that I would get:
>
> i = 0, j = 0
> i = 1, j = 1
> i = 2, j = 2
> ...
> ...
> ...
> i = 9, j = 19
>
> Can this be done in Python?
>
> Thanks.
>   
You can zip two ranges/iterators to produce successive tuples with
values from each iterator respectively, and loop on that:

>>> for i,j in zip(range(10),range(10,20)):
...          print i,j
...
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19

Gary Herron




More information about the Python-list mailing list