Yos Riady optimize for learning

Python List Comprehension

Python list comprehensions are handy shorthands to construct lists in a concise way. It’s like a DSL for building lists!

Let’s start with a simple example. Can you tell what list this code generates?

[n for n in range(10) if (n%2 == 0)]

List comprehensions follow the following syntax:

new_list = [element for element in input_list if some_condition]

Here’s a dictionary comprehension:

my_dict = [dict((k, some_func(k)) for k in input_list]

Constructing a 2d array using nested list comprehensions:

x = [[i*j for i in range(10)] for j in range(10)]
# Creates a 10x10 array (which can depend on i and j if you want)

For kicks, here’s Project Euler Problem 6, solved with list comprehension:

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

a = sum([n**2 for n in xrange(101)])
b = sum(xrange(101))**2
print abs(a-b)

To sum up, python list comprehension are super awesome and you should use it in your projects.

Additional reading:


Here’s the answer to the first question, if you haven’t figured it out:

evens = [n for n in range(10) if (n%2 == 0)]
print evens #[0, 2, 4, 6, 8]


You should follow me on Twitter.

📬 Get updates straight to your inbox.

Subscribe to my newsletter to make sure you don't miss anything.

Here's something you might be interested in...

Going Serverless book

Going Serverless teaches you how to build scalable applications with the Serverless framework and AWS Lambda. You'll learn how to design, develop, test, deploy, and secure Serverless applications from planning to production.

Learn more →