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.
Here’s the answer to the first question, if you haven’t figured it out:
📬 Get updates straight to your inbox!
Subscribe to my newsletter to make sure you don't miss anything.