Bottom Page

Thread Rating:
  • 3 Vote(s) - 3.33 Average
  • 1
  • 2
  • 3
  • 4
  • 5
for loop the difference
Hey guys,

I was reading python learn-stuff at
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?
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
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!


Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Socket creation speed difference Python 2.7 / Python 3.7 PiAil 1 221 Feb-13-2019, 01:55 PM
Last Post: PiAil
  Question about for loop not creating an infinite loop. FWendeburg 1 126 Feb-03-2019, 08:45 PM
Last Post: ichabod801
  whats the difference between sys.exit() and break? mitmit293 1 232 Jan-27-2019, 09:46 PM
Last Post: ichabod801
  python how to find difference between two values hare 1 272 Jan-14-2019, 10:18 PM
Last Post: Gribouillis
  Match CSV files for difference Cuz 4 365 Dec-18-2018, 02:16 PM
Last Post: Cuz
  loop through list or double loop 3Pinter 4 313 Dec-05-2018, 06:17 AM
Last Post: 3Pinter
  Help Convert difference between inputted date and now aspeniii 1 307 Nov-30-2018, 07:31 PM
Last Post: micseydel
  difference between today, and today variables nmrt 2 337 Nov-25-2018, 10:06 AM
Last Post: nmrt
  Difference between self and a reference to own class. (unique instance) Dupletor 1 434 Nov-01-2018, 11:14 AM
Last Post: Gribouillis
  How do I calculate the smallest value that is recognized as a difference when compari AFoeee 1 419 Oct-28-2018, 10:48 PM
Last Post: Gribouillis

Forum Jump:

Users browsing this thread: 1 Guest(s)