# Python List Comprehension

Friday, 12 Jul 2013 · 2 min read ·`python`

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?

List comprehensions follow the following syntax:

Here’s a dictionary comprehension:

Constructing a 2d array using nested list comprehensions:

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.

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

Additional reading:

–

P.S.

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

*📬* Subscribe to my newsletter

Get notified of my latest articles by providing your email below.