[Tutor] what i miss is a C style for loop

Magnus Lycka magnus@thinkware.se
Tue Oct 22 07:46:01 2002


At 22:14 2002-10-22 +1300, Thomi Richards wrote:
>i don't have any concrete examples... I thought "what i need here is a C
>style loop... trouble is, i can't remember where it was.... ahh well...
>probably something like:
>
>for i in range(10):
>         do_something_with(i);
>         i+=3D1;

This is halfways between C and python. :)

First, skip the ; unless you have several statements on the same line.

Second, the python for loop iterates over a sequence, such as a
list. The range operator returns a list. i will be given a new
value from the sequence on each iteration. So:

for i in range(10):
     do_something_with(i)

which is the same as

for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
     do_something_with(i)

This is just like a foreach loop in unix shell script.

If your c program would look like

for (i =3D 5; i < 10, i +=3D 2)
     do_something_with(i);

Your python program will look like:

for i in range(5,10,2):
     do_something_with(i)

With something like:

int i;
int l =3D 10;
int a[len] =3D {1, 5, 6, 2, 3, 4, 9, 0, 7, 8};
int sum =3D 0;

for (i =3D 0; i < l; i++)
     sum +=3D a[i];

you'd do:

a =3D [1, 5, 6, 2, 3, 4, 9, 0, 7, 8]
sum =3D 0
for x in a:
     sum +=3D x

or

a =3D [1, 5, 6, 2, 3, 4, 9, 0, 7, 8]
sum =3D reduce(lambda x,y: x+y, a)

or

from operator import add
a =3D [1, 5, 6, 2, 3, 4, 9, 0, 7, 8]
sum =3D reduce(add, a)

In general, the common C idiom

int length =3D ...;
<some type> a[lenght];
...

for (i =3D 0; i < length; i++):
     do_something_with(a[i]);

becomes

for x in a:
     do_something_with(x)

You don't need to think about any index variable or
bounds checking. A python sequence knows it's own
bounds.

Another C example:

int i;
int l =3D ...;
char source[l] =3D "something";
char target[l];

for (i=3D0; i < l; i++)
     target[i] =3D encrypt(source[i]);

becomes:

source =3D "something"
target =3D map(encrypt, source)

I don't feel that I miss c for loops at all...


--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se