What's the difference between using range() and using a for loop?


Given an list of colors:

colors = ["blue","brown","red","yellow","green"]


for color in colors:


for index in range(len(colors)):

what is the difference between using 1 and 2 ?

Asked By: gabriel-pimentel



With the first one you’ll have access to local variable color within loop. It’s also considered more pythonic.

With the second one you’ll have access to the index instead which might be useful.

I’m not aware of performance difference but someone might be.

Answered By: kabdulla

When you say for color in colors: you are iterating over the items in the list.

for color in colors:

>>> "blue"
>>> "brown"
>>> "red"
>>> "yellow"
>>> "green"

If you iterate over indices you get:

for index in range(len(colors)):

>>> 0
>>> 1
>>> 2
>>> 3
>>> 4

You can get the two version together by using enumerate:

for c, color in enumerate(colors):
    print(c, color)

>>> 0 "blue"
>>> 1 "brown"
>>> 2 "red"
>>> 3 "yellow"
>>> 4 "green"
Answered By: berkelem

Let’s say you want to change each string in the list to uppercase. If you use the first method, each item in the list is basically copied to the temporary variable color. You can change color if you like, but that doesn’t change the list itself.

for color in colors:
    color = color.upper()
>>>['blue', 'brown', 'red', 'yellow', 'green']

When you call range and len, you can change the items in the list, since you have their index.

for index in range(len(colors)):
    colors[index] = colors[index].upper()
>>>['BLUE', 'BROWN', 'RED', 'YELLOW', 'GREEN']
Answered By: teeying
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.