Python language basics 67: iterating over a list with list comprehension
November 28, 2015 2 Comments
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.
Consider the following list of capitals:
capitals = ["Tirana", "Skopje", "Moscow", "Budapest", "Sofia", "Belgrade"]
Say you’d like to reverse each string in the list. Here’s a concise list comprehension solution:
capitals_reversed = [''.join(reversed(capital)) for capital in capitals] print(capitals_reversed)
What’s going on there? Note the elements for the comprehension surrounded by square brackets. The “for capital in capitals” bit will look familiar. It’s the standard foreach loop in Python. It is preceded by a function which expresses what you’d like to do with the current element in the iteration. For each capital in the capitals collection we’d like to construct its reverse and add it to the capitals_reversed collection:
function(item_in_iteration) for item_in_iteration in collection
Here’s the result:
[‘anariT’, ‘ejpokS’, ‘wocsoM’, ‘tsepaduB’, ‘aifoS’, ‘edargleB’]
Here’s how you can capitalise each element in the collection using the same comprehesion style:
capitals_reversed = [capital.upper() for capital in capitals]
[‘TIRANA’, ‘SKOPJE’, ‘MOSCOW’, ‘BUDAPEST’, ‘SOFIA’, ‘BELGRADE’]
In the next post we’ll look at dictionary comprehensions.
Read all Python-related posts on this blog here.