List Comprehension in Python

What is list Comprehension?

This is a method in Python that It allows you to create a new list by transforming and filtering elements from an existing list. The beauty of this is its done in a single line of code. We can use a list and the word iterable interchanged due to a list being an object that can be looped or interated over.

Let’s take a look at how list comprehension is actually structured in Python syntax:

new_list = [expression for item in iterable]

Here is what makes Python list comprehension unique:

  • A single line of code
  • Use any expression, variable, or function to transform and filter elements.
  • Can include multiple for and if statements to create more complex operations, such as nested loops and conditional filtering.
  • Faster than For loops

So for conditional the syntax is as you see below. We will include the conditional after the interable.

new_list = [expression for item in iterable if condition]

What are Some Examples of List Comprehension

Let take a simple example of apply a calculation to a set of list using list comprehension

Apply a calculation to a list of numbers with list comprehension

#get create our data list
import numpy as np 
numbers = [2, 4, 6, 8, 10]

#list comprehension for the square roots
square_roots = [round(np.sqrt(num)) for num in numbers]

 # Output: [1, 2, 2, 3, 3]

List Comprehension with Text

Where list comprehension is essential is when analyzing text documents. We we need to iterate over each individual word. List comprehension becomes an essential technique.

Count the character lengths in words with list comprehension

words =  ["house", "mouse", "chair", "hair"]
lengths =  [len(word) for word in words]
[5, 5, 5, 4]

We can also use this technique to tokenize words in a sentence to create separate words at the end of the sentence. This will create a list of words for use from the previous sentence.

sentence = "There is a mouse in this house"
words = [word for word in sentence.split(" ")]
# Output
['There', 'is', 'a', 'mouse', 'in', 'this', 'house']

Using Conditional with List Comprehension

We an use the “if” conditional to provide a conditional list. This is an easy technique that will allow you place the condition after the iteration. Let’s square the list values if they are divisible by 2.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [x ** 2 for x in numbers if x % 2 == 0]
print(squares)  # Output: [4, 16, 36, 64, 100]
# Output: [4, 16, 36, 64, 100]

In the next example, let’s use list comprehension to filter words that do not meet a length condition.

words = ['apple', 'banana', 'cherry', 'durian', 'elderberry']
long_words = [word for word in words if len(word) > 6]
print(long_words)  # Output: ['banana', 'elderberry']
# Output: ['banana', 'elderberry']

Filtering with List Comprehension

We can use the list comprehension and conditional to filter a list in by adding the “in” or “not in” parameter. In this example, we will use list comprehension to filter mixed list of values from a existing list of values:

symbols = ["%","$",".","#","@"]
mixed_list = ["bike","%","kite",1,"@","who","$"]
no_symbols = [word for word in mixed_list if word not in symbols]
['bike', 'kite', 1, 'who']

Complex Examples of List Comprehension

So, let’s bring together many techniques that we have use before in a complex example.

In this example, we use list comprehension to create a new list result that contains all words from the words list that are longer than five letters and contain at least one vowel. Here’s how the list comprehension works:

  • The outer loop iterates over each word in the words list.
  • The first if statement filters out words that are not longer than five letters.
  • The inner loop iterates over each letter in the current word.
  • The second if statement filters out words that do not contain any vowel.
  • The word.upper() expression transforms the current word to uppercase.
  • The resulting words that meet all the conditions are added to the result list

Here is what we will end up with

words = ['apple', 'banana', 'cherry', 'durian', 'elderberry']
vowels = ['a', 'e', 'i', 'o', 'u']
result = [word.upper() for word in words if len(word) > 5 for letter in word if letter in vowels]
# Output: ['ELDERBERRY']

Gaelim Holland

Notify of

Inline Feedbacks
View all comments