Changing Lists: range vs Comprehensions

A common scenario where you may use the range() and len() in combination with for loop is when you want to change a list as it is being traversed.

Let’s add 1 to every item in the list L1. A simple for loop won’t work.
To change the list as you go throught it, we need to use indexes so we can assign an updated value to each position as we go. range() and len() in combination can produce the required indexes.

>>> L1 = [1, 2, 3]
>>> for l in range(len(L1)):
...     L1[l] += 1
... 
>>> L1
[2, 3, 4]

A simple for loop iterates through actual items, not list positions. A while loop can achieve the same result but requires a bit more work and might run more slowly.

>>> L1 = [1, 2, 3]
>>> l = 0
>>> while l < len(L1):
...     L1[l] += 1
...     l += 1
... 
>>> L1
[2, 3, 4]

Leave a Reply