43  Python Comprehensions

43.1 List Comprehensions

It is a way of creating lists without loops. Comprehensions could be a more readable solution instead of loops. Every list comprehension could be written by normal loops.

Lets start with following python loop. This loop creates squared numbers from 0 to 9. Resulting numbers should 0,1,4,9,…81

l2 = []
for x in range(10):
    l2.append(x*x)
print(l2)

List comprehensions code would be:

l1 = [x*x for x in range(10)]
print(l1)

Template for simple list comprehension is:

[expression for item in iterable]

Another interesting example. Change a list of strings to list of integers

str_list = ["1", "2", "3", "4", "5"]
int_list = [int(x) for x in str_list]

As could be seen from above example, we could call functions in the comprehensions.

name_list = ["atilla","aydın","duru"]

l2 = []
for name in name_list:
    l2 = l2 + [name.capitalize()]
print(l2)

l1 = [name.capitalize() for name in name_list]
print(l1)

43.1.1 Filtering

Filtering the list is a common operation. loop version:

l2 = []
for x in range(10):
    if x % 3 == 1
        l2.append(x*x)
print(l2)

In list comprehension, we could also filter items in the iterable with optional if

l2 = [x*x for x in range(10) if x % 3 == 1]
print(l2)

43.2 Double loop example

Following code creates pairs using for loop:

pairs = []
for i in range(3):
    for c in ["a","b","c"]:
        pairs.append((i, c))

print(pairs)

Comprehension version is more compact.

pairs = [(i, c) for i in range(3) for c in ["a","b","c"]]

print(pairs)

43.2.1 Tutorials/Videos for list comprehension

43.3 Dictionary Comprehensions

Dictionary Comprehension are very similar to list comprehension. Instead of [], dictionary symbol {} is used. Following code creates squares version using dictionary and for loop.

squares = {}
for x in range(5):
    squares[x] = x ** 2

print(squares)

Dictionary comprehension is more compact.

squares = {x: x ** 2 for x in range(5)}

print(squares)

43.4 Set Comprehensions

Set comprehensions are very similar to list comprehensions, use {} to create sets instead of []. Since we create sets, there are no duplicates and output may be unordered.

Following creates list

nums_list = [x % 3 for x in range(10)]
print(nums_list)

Following creates set

nums_set = {x % 3 for x in range(10)}
print(nums_set)

Output will be different:

  • nums_list: [0, 1, 2, 0, 1, 2, 0, 1, 2, 0]
  • nums_set: {0, 1, 2}

In set version, no duplicates exist.