List, Dict, and Set Comprehensions in Python 3

Last updated on November 10, 2022 A Goodman Loading... Post a comment

A few examples of using list, dict, and set comprehensions in Python 3.

Example 1: List Comprehension

This example creates a list that contains numbers that are greater or equal to 10 based on a given list of numbers.

The code:

numbers = [-3, 4, 1, 2, 9, 8, 10, 20, 30, 11, 13, 14]

numbers_greater_than_10 = [item for item in numbers if item >= 10]


[10, 20, 30, 11, 13, 14]

Example 2: Deep Nested List Comprehension

This example demonstrates how to deal with a list with multi-level nestings. Let’s say we have a list of lists containing words from different sources. Our goal is to form a new list with words whose lengths are greater or equal to 7. Here’s we get it done:

data = [
                    ['apple', 'banana', 'coconut'], 
                    ['candy', 'cookie', 'bomb'], 
                    ['Albania', 'Canana', 'American', 'China', 'Bolivia']

long_words = [word for words in data for word in words 
                   if len(word) >= 7



['coconut', 'Albania', 'American', 'Bolivia']

Example 3: Dict Comprehension

Let’s say we have a list of strings and what we want is a dictionary whose keys and values are the strings and their index in the list, respectively.

animals = ['ant', 'tiger', 'crocodile', 'dragon', 'chicken', 'duck', 'flamingo']
dict = {key : value for key, value in enumerate(animals)}


 0: 'ant',
 1: 'tiger',
 2: 'crocodile',
 3: 'dragon',
 4: 'chicken',
 5: 'duck',
 6: 'flamingo'

Example 4: Set Comprehension

A simple set comprehension example with numbers.

The code:

numbers = [1, 2, 3, 1, 4, 3, 5, 9, 18, 22]

set = {number for number in numbers}


{1, 2, 3, 4, 5, 9, 18, 22}


We’ve walked through some examples of using list, dict, and set comprehensions in Python 3. This is a wonderful feature that can help us quickly create new objects by filtering and transforming the elements of a collection. If you’d like to explore more awesome stuff in Python then take a look at the following articles:

You can also check out our Python category page for more tutorials and examples.

Notify of
Inline Feedbacks
View all comments

Related Articles