Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Now that we’ve seen how the iteration protocol works, let’s
turn to a very common use case. Together with for loops, list comprehensions are one of
the most prominent contexts in which the iteration protocol is
applied.
In the previous chapter, we learned how to use range to change a list as we step across
it:
>>>L = [1, 2, 3, 4, 5]>>>for i in range(len(L)):...L[i] += 10... >>>L[11, 12, 13, 14, 15]
This works, but as I mentioned there, it may not be the optimal “best-practice” approach in Python. Today, the list comprehension expression makes many such prior use cases obsolete. Here, for example, we can replace the loop with a single expression that produces the desired result list: