[Tutor] Beginner's question: Looping through variable & list simultaneously

Steven D'Aprano steve at pearwood.info
Tue Dec 3 16:58:02 CET 2013


On Tue, Dec 03, 2013 at 04:03:55PM +0100, Rafael Knuth wrote:
> Hej there,
> 
> > That's very poor coding, if you're given a function that does exactly what
> > you want, why rewrite it and worse still, get it wrong?
> 
> I don't quite understand. I took that advice, tried it - it worked,
> and then I figured out there's also another way to get there.
> The output from the "for Country in range(len(PopularCountries))" is
> exactly the same as with "enumerate", or am I missing something here?

Looping over indexes, then extracting the item you actually want, is 
considered poor style. It is slower, less efficient, more work to write, 
harder to read. Instead of writing this:


for i in range(len(some_list)):
    item = some_list[i]
    process(item)


it is more "Pythonic" to do this:

for item in some_list:
    process(item)



-- 
Steven


More information about the Tutor mailing list