Thinking Outside the for Loop with List Comprehensions

Sujan ShresthaSujan Shrestha
2 min read

Imagine writing a long for loop to create a list in Python, only to find that there is another simpler, more concise way to do the same thing. And that is exactly what List Comprehension in Python is.

The Python documentation defines it as:

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

The syntax for List Comprehension goes like this:

[expression for item in iterable if condition]
  • expression: The operation or value applied to each item before it is added to the new list.

  • item: The current value being iterated over from the iterable.

  • iterable: An iterable, i.e. list, tuple, set, dictionary, range, etc.

  • if condition (optional): A filtering condition to determine if an element is to be included or not.

With this syntax, the whole for loop block is condensed into a single line.

Example

even = []

for n in range(10):
    if n % 2 == 0:
        even.append(n)

The code above creates a list of even numbers less than 10. The code spans 4 lines and has indentations. It is also necessary to initiate an empty list before we run the for loop to add the values to the list.

Now let’s look at the same functionality using a List Comprehension.

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

Amazing! This looks so much simpler. The list is initiated with the functionality, it only spans a single line, and it is much more concise. Here is the breakdown:

iterable: range(10)

item: n

if condition: n%2 == 0

expression: n (here, no transformation is done on the final value)

Now, we talked about expression in the syntax, and that it can be used to transform the final value before being added to the list. Let’s take a look at how we can do that.

For example, let’s create a list of the squares of all the even numbers from 0 to 9. We can do this by tweaking the expression part of the last code.

squares_of_evens = [n * n for n in range(10) if n % 2 == 0]
0
Subscribe to my newsletter

Read articles from Sujan Shrestha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sujan Shrestha
Sujan Shrestha