Loops and things

i.pantusa at gmail.com i.pantusa at gmail.com
Fri Dec 14 15:42:46 EST 2007


On Dec 14, 5:01 pm, Neil Cerutti <horp... at yahoo.com> wrote:
> On 2007-12-14, rocco.ro... at gmail.com <rocco.ro... 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?
>
> Yes, assuming you meant to say:
>
> i = 0, j = 10
> i = 0, j = 11
> ...
> i = 9, j = 19
>
> import sys
> from itertools import izip
>
> for i, j in izip(xrange(10), xrange(10, 20)):
>   sys.stdout.write("i = %d, j = %d\n", (i, j))
>
> --
> Neil Cerutti
> To succeed in the world it is not enough to be stupid, you must also be well-
> mannered. --Voltaire

Yeah, that's what I meant ... ooops :)

Thanks a lot to everyone for the useful info. In the meantime I had
found out about zip and that way of doing it. But I really appreciated
all the different alternative solutions that were illustrated,
especially the more "functional" ones with map ... very cool, I'm also
a big Lisp fan, and I really dig those.



More information about the Python-list mailing list