Python Forum
[Basic] Never use "for i in range(len(sequence)):"
Thread Rating:
  • 4 Vote(s) - 3.25 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Basic] Never use "for i in range(len(sequence)):"
#1
This will be pretty short and to the point, but I find my self typing this out far too often these days and want something to link to.

Most languages around today have some type of for loop syntax.  Python is no different; in fact, in python for loops are highly preferred in most circumstances over while loops.

In languages like C one loops like this:
for (i=0; i<length_of_sequence; i++)
In the above we are getting indexes from our for loop.

Many Python beginners, whether they be coming from other languages like C, or brand new to programming, inevitably go through a phase where they try to do the same thing.

This results in things like this:
for i in range(len(sequence)):
    print(sequence[i])
This is never the right answer.  In python we have the power and ability to loop directly over the items in a sequence.

We can instead do this:
for item in sequence:
    print(item)
It is simpler to type; simpler to read; and most importantly makes more sense.  As we were never concerned with the index to begin with, we don't need to bother with it.

There are however cases in which one does want the index as well as the item.  In such cases enumerate is the tool of choice.

Our loop becomes:
for i,item in enumerate(sequence):
    print("{} : {}".format(i,item)
In short, if you ever catch yourself writing range(len(sequence)) rethink your goal and figure out what it really is you are interested in.

See this great article from Ned Batchelder for more info on how to iterate effectively.
-Mek


Messages In This Thread
Never use "for i in range(len(sequence)):" - by Mekire - Oct-06-2016, 10:23 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020