Numeric for loop
Posted: Tue Mar 25, 2008 12:44 am
In development, I added the new "for" loop syntax for the numeric for loop. The old syntax will still be supported for one year, but its use of .. ++ and -- didn't match anything else in the language. The new syntax uses the same "for x in" as an "enumerable for loop" and the rest of the statement matches slicing (list[start:stop:step]):
The integers generated match the indexes of a list (or array), whether the entire thing or a slice.
Unlike the old numeric for loop, the parameters to the loop are evaluated only once. In other words, the "stop" and the "step" are not re-evaluated each iteration of the loop. I think this is more clear and can also be more efficient. It's also more like using a range() function or enumerator.
If you need to re-evaluate the boundary and/or step each time, use the general purpose "while" loop.
# forms:
for x in start : stop : step
print x
for x in start : stop # step of 1 is assumed
print x
for x in stop # start of 0 is assumed
print x
# examples:
list = ['qwerty', 'dvorak']
for i in list.count
list[ i] = list[ i].toUpper
for i in 0 : 100 : 2
print i
The integers generated match the indexes of a list (or array), whether the entire thing or a slice.
Unlike the old numeric for loop, the parameters to the loop are evaluated only once. In other words, the "stop" and the "step" are not re-evaluated each iteration of the loop. I think this is more clear and can also be more efficient. It's also more like using a range() function or enumerator.
If you need to re-evaluate the boundary and/or step each time, use the general purpose "while" loop.