List Comprehensions (python 3)


List Comprehensions (python 3) Author: Mohammad Amaan Abbasi | July 14, 2018

list comprehension offers a succint way to create lists. The key to understand list comprehensions is that they're just for-loops but expressed in a more compact syntax.

This post is intended to help beginners get familiar with the topic and know when and when not to use list comprehensions. I recommend that you write code as you read the post.

A Basic example


Let’s take a simple example, This list comprehension creates a list based of a string:

letters = [letter for letter in "pengoox"]
print(letters)

Output:    
['p','e','n','g','o','o','x']

This was fairly simple. The list we created consists of the letters in the string 'pengoox'.

Take a look at this example:

squares = [x*x for x in range(11)]  //range(11)->0-10, 11 is not included

It computes the list of all integer square numbers from zero to 10:

print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]    

Looks intuitive right?
Don’t worry if it feels a bit foggy, just bear with me, it will become more clear as we proceed. Let’s break it down into smaller chunks.

range(11) it is a collection or a iterable. x is an item and lastly x*x is the expression. Basically we are iterating over a collection of values, in our case it is a range of numbers between 0-11, squaring them and storing them into a list squares.

Now let’s convert the above example into a plain for-loop:

squares = []
for square in squares:
    squares.append(square*square)
print(squares)    

Output will be the same. If you look closely and compare the for-loop with the List comprehension example above, you will spot some similarities. They both are doing the same work but List comprehensions are more terse than for-loops.

General pattern:


List comprehension:

values = [expression for item in collection]

For loops:

values = []
for item in collection:
    values.append(item)

Using “if” with List Comprehensions


List comprehensions can utilize conditional statements to modify existing list.
Let’s take the squares example and add a condition to it:

even_squares = [pow(x,2) for x in range(11) if x % 2 == 0]

This list comprehension compute a list of the squares of all even numbers ranging between 0-11.

print(even_squares)

[0,4,16,36,64,100]

You can further add a statment to the above loop:

squares = [pow(x,2) for x in range(11) if x % 2 == 0 and x > 5]
print(squares)

[36, 64, 100]

By now, you should have realize how powerful list compreshensions are. They are little shortcuts that makes your code more elegant.

General pattern


List comprehensions:

values = [expression for item in collection if condition]

For-loop:

values = []
for item in collections:
    if condition:
        values.append(expression)

Nested Loops in a List Comprehensions


This will be fairly easy to understand. This time instead of executing just one loop we’ll have more than one loop. lets make the for-loop first and then we’ll convert it into a List Comprehension.

xy = []

for x in [1,2,3]:
    for y in [4,5,6]:
        xy.append(x*y)
print(xy)

[4, 5, 6, 8, 10, 12, 12, 15, 18]

This code multiplies each item in the first list with each item of the second list.

Now before you see the List Comprehension equivalent of the for-loop, I want you to give it a try.

Alright, I hope you have tried it yourself and you might have got something like:

xy = [x * y for x in [1,2,3] for y in [4,5,6]]
print(xy)

4, 5, 6, 8, 10, 12, 12, 15, 18

You can add more loops and use if conditions, but make sure your code is penetrable, use List comprehensions wisely, as you get better at writing list comprehensions, it will become easier to write code that’s difficult to read.

Takeaways


  • Comprehensions provides a concise syntax, hence limiting our lines of code.
  • Use Comprehensions wisely, don’t compromise readability for saving a few lines, use a for-loop instead.

More Resources