using range() in for loops
Alex Martelli
aleaxit at yahoo.com
Wed Apr 5 23:14:23 EDT 2006
Georg Brandl <g.brandl-nospam at gmx.net> wrote:
> Steven D'Aprano wrote:
> > On Wed, 05 Apr 2006 16:15:12 +0200, Georg Brandl wrote:
> >
> >> sushant.sirsikar at gmail.com wrote:
> >>> hi John,
> >>> Python doesn't provide for loop like C / C++ but using Range() or
> >>> Xrange() you can achive all the functionalities of the C for loop.
> >>
> >> Not quite.
> >
> > Care to explain what the differences are, or shall we guess?
>
> C's for is much more powerful.
>
> for(a; b; c) { d } translates to
>
> a
> while b
> d
> c
>
> which can't be replaced by a simple
>
> for i in range(...)
No, but it can be easily replaced by:
# factoring out the loopstructure...
def gotcha():
a
while b:
yield c
# ...from the loopbody
for i in gotcha():
d
or several variations thereof. In C++, I almost half-heartedly replace
most of Python's generators' power with C++'s templated iterators, but
when I program in C I find myself really straightjacketed these days in
NOT being able to pull out the "loopstructure" as I can in Python (and,
about halfway, in C++).
Alex
More information about the Python-list
mailing list