Python Forum

Full Version: in tutorials: Never use "for i in range(len(sequence)):
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i just saw this tutorial.  i have had a couple cases where i needed the index in the loop, or the index of where i broke out of the loop.

i also made macros to step through lists and dictionaries directly and made extensive use of them. but that was back in my assembler days. i also made functions like that in C and used those a lot.  my AVL code in C has like functions (to step forward or backwards in a tree/mapping/dictionary).

one thing i like in python is that one can do things either way. but i have not, yet, run into a need to use goto in python. where would i go, anyway? the only use of goto i every made in C was to go to error handlers/cleanups at the end of function. python has exception handling, instead.
Quote:i have had a couple cases where i needed the index in the loop, or the index of where i broke out of the loop.

The point isn't that you never need the index, but that you are much more likely to need the object itself.  In cases where you do need the index, enumerate is almost always the best tool as it gives access to the object and the index.  If you need the index because you are trying to iterate over two sequences in parallel, you should probably be using zip instead.

Quote:the only use of goto i every made in C was to go to error handlers/cleanups at the end of function. python has exception handling, instead.
And exceptions can actually be abused quite badly to this end as well; though at least you can't arbitrarily jump back in time.