3 ms·
Noob question: Why is it bad to use for i in range(len(foo))? Because you can just use for bar in foo?
by Gasp0de 8y ago
Noob question: Why is it bad to use for i in range(len(foo))? Because you can just use for bar in foo?
- snazz 8y agoYes. 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.
- tgb 8y agoAnd when your actually need the index, generally you use enumerate(foo).
- futureastronaut 8y agoIt'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.
- SilurianWenlock 8y agoWhere are you meant to learn this?
- xkcd-sucks 8y agohttps://docs.python.org/3/ 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
- futureastronaut 8y agoPython's list of built-in functions is fairly small https://docs.python.org/3/library/functions.html#built-in-funcs 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).
- progval 8y agoReading other people's code (usually while improving it)
- avip 8y agoIt's not "bad", but it's generally unnecessary. And breaks on generators.