Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difficulty finding a Python 3.x implementation of the familiar C for-loop

I'm inexperienced in Python and started with Python 3.4.

I read over the Python 3.x documentation on loop idioms, and haven't found a way of constructing a familiar C-family for-loop, i.e.

   for (i = 0; i < n; i++) {
       A[i] = value;
   }

Writing a for-loop like this in Python seems all but impossible by design. Does anyone know the reason why Python iteration over a sequence follows a pattern like

for x in iterable: # e.g. range, itertools.count, generator functions
    pass;

Is this more efficient, convenient, or reduces index-out-of-bounds exception?

like image 1000
codeReview Avatar asked Nov 28 '22 20:11

codeReview


2 Answers

for lower <= var < upper:

That was the proposed syntax for a C-style loop. I say "was the proposed syntax", because PEP 284 was rejected, because:

Specifically, Guido did not buy the premise that the range() format needed fixing, "The whole point (15 years ago) of range() was to *avoid* needing syntax to specify a loop over numbers. I think it's worked out well and there's nothing that needs to be fixed (except range() needs to become an iterator, which it will in Python 3.0)."

So no for lower <= var < upper: for us.

Now, how to get a C-style loop? Well, you can use range([start,]end[,step]).

for i in range(0,len(blah),3):
    blah[i] += merp #alters every third element of blah
                    #step defaults to 1 if left off

You can enumerate if you need both index and value:

for i,j in enumerate(blah):
    merp[j].append(i)

If you wanted to look at two (or more!) iterators together you can zip them (Also: itertools.izip and itertools.izip_longest)

for i,j in zip(foo,bar):
    if i == j: print("Scooby-Doo!") 

And finally, there's always the while loop

i = 0
while i < upper:
    A[i] = b
    i++

Addendum: There's also PEP 276, which suggested making ints iterable, which was also rejected. Still would have been half-open

like image 188
NightShadeQueen Avatar answered Dec 06 '22 16:12

NightShadeQueen


range(n) produces a suitable iterable :)

for i in range(n):
    A[i] = value

for the more general case (not just counting) you should transform to a while loop. eg

i = 0
while i < n:
    A[i] = value
    i += 1
like image 30
John La Rooy Avatar answered Dec 06 '22 15:12

John La Rooy