For loops with explicit indices -- again
Greg Ewing
greg at cosc.canterbury.ac.nz
Tue Mar 19 21:27:23 EST 2002
Armin Rigo wrote:
>
> it = iter(lst)
> for x in it:
> if x>0:
> lst[it.count-1] -= 1
I find this ugly, particularly the need to use count-1
rather than just count. It's just begging for off-by-one
errors.
> it.count += 1 # skip next element
> it.count -= 1 # process the same element again
> it.count = 0 # full rewind
> it.count -= 1; del lst[it.count] # remove bad item from list
This is even worse! It's tantamount to modifying
a loop control variable inside the loop, which is
widely regarded as a Bad Thing To Do from a
maintainability standpoint.
If the ability to modify the count is dropped,
I see nothing that can't be achieved more elegantly
using an iterator-wrapper such as the proposed
indexed() function that returns (index, value)
pairs.
--
Greg Ewing, Computer Science Dept, University of Canterbury,
Christchurch, New Zealand
To get my email address, please visit my web page:
http://www.cosc.canterbury.ac.nz/~greg
More information about the Python-list
mailing list