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):
*x)
l2.append(xprint(l2)
List comprehensions code would be:
= [x*x for x in range(10)]
l1 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.
= ["atilla","aydın","duru"]
name_list
= []
l2 for name in name_list:
= l2 + [name.capitalize()]
l2 print(l2)
= [name.capitalize() for name in name_list]
l1 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
*x)
l2.append(xprint(l2)
In list comprehension, we could also filter items in the iterable with optional if
= [x*x for x in range(10) if x % 3 == 1]
l2 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.
= [(i, c) for i in range(3) for c in ["a","b","c"]]
pairs
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):
= x ** 2
squares[x]
print(squares)
Dictionary comprehension is more compact.
= {x: x ** 2 for x in range(5)}
squares
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
= [x % 3 for x in range(10)]
nums_list print(nums_list)
Following creates set
= {x % 3 for x in range(10)}
nums_set 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.