for loop the difference - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: for loop the difference (/thread-15269.html) |
for loop the difference - 3Pinter - Jan-10-2019 Hey guys, I was reading python learn-stuff at https://www.programiz.com/python-programming/for-loop and I was wondering: is the suggested code logical? # Program to iterate through a list using indexing genre = ['pop', 'rock', 'jazz'] # iterate over the list using index for i in range(len(genre)): print("I like", genre[i])If I had to code it: I would (a newbie at python!): # Program to iterate through a list using indexing genre = ['pop', 'rock', 'jazz'] # iterate over the list using index for i in genre: print("I like", i)I don't understand why range+len is needed. Perhaps someone can clearify? RE: for loop the difference - buran - Jan-10-2019 Your code is definitely better, with the recommendation to use more descriptive names like genres = ... and for genre in genres: instead of i . We even have special thread in Tutorials - Never use "for i in range(len(sequence)):"I looked at the article in your link - note that it's just an example, i.e. they show the more pythonic way first and they also show what you can do too using index. In other words I would say it's just for educational purposes RE: for loop the difference - 3Pinter - Jan-10-2019 Ok, thanks for clearifying Buran, Sometimes I have to check if I understand it all correctly. And since there are often more than one ways of achieving things (and sometimes with surprisingly faster timed versions), I'm curious which is better and/or why things are done this way. Thanks for your suggestion regarding "genre" vs. "i". Noted! 3Pinter |