Python List Comprehension By Example

Let’s go through four increasingly complex examples of list comprehension so you can learn by example.

Python List Comprehension By Example

List comprehension is the way that Python interprets and constructs lists, which are synonymous with Arrays for those coming from a different language background. The elegance of Python list comprehension can make reading code difficult at first, but once you get the hang of it using list comprehension can feel like downright cheating because it’s so simple and fast.

Let’s go through four increasingly complex examples of list comprehension so you can get the hang of it and go forth spreading the Pythonic word!


1: Simple List of Items

This is the simplest example of list comprehension and is something that is analogous in a number of different languages. All the technique requires is to list—pun intended—each item separated by commas nested inside of square brackets. You can create a nested list just as easily.


2: Using a For Loop

This is where things start to get interesting. Python for loops are very flexible as iterators. Use this technique to perform an operation on each item during the comprehension.

I use this technique when working with a list of dictionaries to reference a specific term in each dictionary.


3: Nested For Loops

This is where I got lost reading list comprehensions. My recommendation is to break it up into multiple lines like I’ve been doing in this article and read from the top down. It will save you time and headache.


4: For Loop With Conditional Statement

Okay, you’re telling me that it’s possible to iterate through a list, perform a conditional check on each item, perform an operation on the passing items, and store the result in one line? That’s right, an absolute game changer!


What are some of your favorite list comprehension techniques? Share them in the comments below and help spread the Pythonic word!

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe