Python language basics 67: iterating over a list with list comprehension

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.

List 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.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to Python language basics 67: iterating over a list with list comprehension

  1. Pingback: Python language basics 67: iterating over a list with list comprehension | Dinesh Ram Kali.

  2. Pingback: Python language basics 68: iterating over a dictionary with dictionary comprehension in Python | Dinesh Ram Kali.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

My goal with this blog is to offend everyone in the world at least once with my words… so no one has a reason to have a heightened sense of themselves. We are all ignorant, we are all found wanting, we are all bad people sometimes.

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: