loading...

What are Python Comprehensions?

dev0928 profile image dev0928 ・2 min read

Python has a powerful feature called comprehensions. With this comprehension feature, a new sequence can be built based on another sequence with added calculation logic in a succinct way. Python 2.0 introduced list comprehensions. Dictionary and set comprehensions were introduced in Python 3.0. This article covers various types of comprehensions with examples.

List Comprehension

Let’s try to understand comprehension with an example. Let’s say we have a list of numbers. We want to build a new list that contains double of every odd number from the original list. New list with above requirements can be created using list comprehension:

nums = [11, 21, 30, 40, 55, 66, 17]
odd_nums = [n*2 for n in nums if n % 2 != 0]    # output is [22, 42, 110, 34]

Let’s break down the above statement to understand the structure of comprehension.

Comprehensions generally have below parts:

  • An input sequence - nums in the above example which is a list
  • A variable representing individual members of the sequence - n in the above example
  • An optional predicate - if n % 2 != 0 we are filtering odd numbers from the original list
  • An output expression - n*2 this double the filtered odd numbers

Here is an illustration outlining different parts of the list comprehension:

Comprehension Representation

Here are few more list comprehension examples:

nums = [1, 2, 3, 4]
#Get a new list containing square of the numbers
sq_nums = [n*n for n in nums]      # [1, 4, 9, 16]
fruits = [Apple, Banana, Orange]
#convert list to lowercase
l_fruits = [name.lower() for name in names]  #[‘apple’, ‘banana’, ‘orange’]

Set Comprehension

We can create set sequences using set comprehensions. Let’s say we have a list containing duplicate numbers and we want to create a set without duplicates. Also, the resulting sequence should be double of the original numbers. This can be achieved using set comprehension. Please note as sets don’t maintain order of elements, resulting sequence's members could be arranged in any random order.

dup_nums = [1, 2, 2, 3, 4, 5, 12, 10, 2]
sq_set = {num*2 for num in dup_nums} # {1, 4, 100, 9, 16, 144, 25}

Dictionary Comprehension

Here is an example of dictionary comprehension creation, containing number as its key with square of the number as its value

 d = {n : n*n for n in range(1, 6)}     # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Tuple Comprehension

There are no tuple comprehensions in Python. Python generators could be used to create tuples in a similar succinct way.

Discussion

pic
Editor guide