Everything About Python List Comprehension

by:

Python

Python List Comprehension is one of my favorite things when coding. Using it, you can accomplish most things you would do with a regular loop, but much simpler and faster.

Understanding a Python List comprehension

In simple words, a list comprehension is executing a for loop inside of a list including conditions (optional). The image below presents how a list comprehension is defined in python:

There are 3 parts to it:

  • Output: Output variable as a result of the for loop
  • Variable: Variable part of the for loop
  • Condition: You can even an if condition to define what shows in the final output

When executing

The example the code above which return even number in a list of integers, it prints

>>> [2, 4]

The same task could be implemented with a list comprehension, but it would be more code rather than just one code – see bellow

my_temp_list = []

for x in [1, 2, 3, 4]:
    if x % 2 == 0:
        my_temp_list.append(x)

if-else statement

Not surprisingly, the python list comprehension also allows and an if-else statement rather than just an if statement as shown on previously. However, the if-else statement will need to be moved to the front of the list rather than in the end.

[(x, "is even") if x % 2 == 0 else (x, "is odd") for x in [1, 2, 3, 4]]

The list comprehension above classifies as a list of tuples if a number “is even” or “is odd” and keep the original variable value.

Main list comprehension criticism

More important than writing code that does what you need is to write code that everybody can run. One of the main criticisms of the list comprehension is that is is not easy to easy, thus be careful when using it because it may be a problem when trying to understand what is happening.

List comprehension performance

List comprehension is ara faster than for loops! This happens because the list comprehension is optimized for the interpreter to spot a predictable pattern when looping.

In conclusion, I hope you can see the beauty in the list comprehension the same way I do. It performs faster, but be careful with its readability.

Related Posts