8 Levels of Using List Comprehension in Python

Yang Zhou
Yang Zhou
Oct 14, 2020 · 4 min read

Introduction

This post will demonstrate 8 levels of using the list comprehension from elementary to profound. After understanding all the 8 levels, mastering the list comprehension will be just a piece of cake. 🍰

Level 0: Know the Template of the List Comprehension

Every list comprehension should abide by the template as following:

my_list=[ expression for item in iterable (if condition) ]

It’s very neat and simple. Just two square brackets including three key components:

  • A for-loop to iterate an iterable
  • An expression to deal with the item
  • An optional if condition

Next, let’s take a look at how to write ingenious programs with this simple template.

Level 1: Just Replace For-loops

Compared the following for-loop version implementation, this is already a big step to a Pythonic and elegant program.

Actually, all iterables in Python can be used in a list comprehension. Another example:

As the above example shown, we can get the maximum value of each row in a matrix with only one line of code.

Level 2: Use the If Condition Smartly

Use the if condition smartly

Level 3: Use a More Complex Expression

Even including an if...else... statement:

Note: There is one issue that could be confusing if you haven’t really understood the list comprehension template:

The if...else... statement, also called ternary conditional operator, in the expression is different with the optional if condition at the last of the list comprehension template. Let’s review the template:

my_list=[ expression for item in iterable (if condition) ]

As the template shown, the last if condition is one of the components of a list comprehension. We can’t add an else statement after it since the syntax of list comprehension does not support that.

The expression part can be any expressions as long as it follows the Python expression’s syntax. If we use an if , there must be an else as well since it’s the ternary conditional operator syntax of the Python expression.

Level 4: Use Nested For-Loops to Handle Nested Iterables

The above program is equal to:

Which implementation is better? The answer is so obvious. 😃

Of course, we can put more nested for-loops in one list comprehension, but it’s not a good idea. The best practice is never using more than two for-loops in one comprehension for the readability sake.

In addition, we can add the optional if conditions after any for-loops:

Level 5: Avoid Higher Order Functions for Readability

The map() method can always be replaced:

L = map(func, iterable)
# can be replaced to:
L = [func(a) for a in iterable]

The filter() method can be converted as well:

L = filter(condition_func, iterable)
# can be converted to
L = [a for a in iterable if condition]

Let’s see an example, the following lists (L1 and L2) implemented by two different ways have the same result:

Same result lists implemented by two ways

Level 6: Use Generator Expressions to Reduce Memory Costs

The generator expression can reduce the memory costs by avoiding producing a full list, because a generator applies lazy evaluation.

Level 7: Understand the Philosophy Behind the List Comprehension

Conclusion

Thanks for reading!

Relative articles:

TechToFreedom

Dive into technology, investment and entrepreneurship.

Yang Zhou

Written by

Yang Zhou

Software Engineer | Investor | Entrepreneur yangzhou1993.medium.com/follow

TechToFreedom

Technology should and must give each individual greater freedom.

Yang Zhou

Written by

Yang Zhou

Software Engineer | Investor | Entrepreneur yangzhou1993.medium.com/follow

TechToFreedom

Technology should and must give each individual greater freedom.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store