Python language basics 67: iterating over a list with list comprehension
November 28, 2015 2 Comments
Introduction
In the previous post we looked at a practical example using the yield keyword in Python. The function distributed an integer across a number of groups as equally as possible.
In this post we’ll look at an interesting language construct called comprehension. A comprehension in Python is a form of iteration which provides a concise and expressive way of iterating over a collection. In particular we’ll consider list comprehensions, but keep in mind that comprehensions can be applied to any iterable object, such as sets, tuples or generator functions. The delimiting element, such as curly braces for sets and square brackets for lists will determine the type of object returned by the comprehension.