Hacker News new | ask | show | jobs
by Gasp0de 2656 days ago
Noob question: Why is it bad to use for i in range(len(foo))? Because you can just use for bar in foo?
3 comments

It's mostly a bikeshed and a signaling thing. Only a "noob" wouldn't know about enumerate(), right? The program could be brilliant in much higher level ways, but mid/senior only-knows-Python hot shot will jump on your anti-idiom like a dog on a dropped hamburger. Including such anti-idioms in your public code can filter out people like that.
Where are you meant to learn this?
Python's list of built-in functions is fairly small https://docs.python.org/3/library/functions.html#built-in-fu... (but to be clear, I wouldn't ding somebody for forgetting about one of them).
Reading other people's code (usually while improving it)
https://docs.python.org/3/

Consider that your iterable may not be a list, and may not actually have a "length" prior to its being consumed

Yes. Iterating over a range of integers equal to the length of an iterable is really clunky compared to iterating directly over the iterable. Plus, if you actually want to use one of the elements of the list, for instance, in the body of the loop, you would have to do foo[i] instead of referring to it as bar.
And when your actually need the index, generally you use enumerate(foo).
It's not "bad", but it's generally unnecessary. And breaks on generators.