Comprehension¶
defining comprehension
conditional statements and comprehension
dictionary comprehension
Comprehension is a nice way to build lists, sets, and dictionaries. First let’s build a list from a string using a loop.
alphabet = 'abcdefghijklmnopqrstuvwxyz'
>>> list = []
>>> for letter in alphabet:
... list.append(letter)
>>> list
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
Every list comprehension has three parts: (1) a member, (2) an expression, and (3) an iterable. A conditional is optional and can be used to control membership. Here are the forms of list comprehension:
[expression for member in iterable]
[expression for member in iterable (if conditional)]
[expression (if conditional) for member in iterable]
Now we will construct the same list we construct with a loop using a comprehension.
>>> [letter for letter in alphabet]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z]
Note that we by using conprehension we reduced the construction to one easy-to-read line.
Here are some examples using conditionals along with comprehension.
new_list = [expression for member in iterable (if conditional)]
vowels1 = {i for i in alphabet if i in 'aeiou'}
print('The vowels are', vowels1)
new_list = [expression for member in iterable (if conditional)]
Here we generate a set to show that comprehension can be used to generate sets.
consonants = {i for i in alphabet if i not in 'aeiou'}
print('The consonants are', consonants)
new_list = [expression (if conditional) for member in iterable]
delete_vowels = [letter if letter not in 'aeiou' else '*' for letter in alphabet]
print('Letters with vowels marked', delete_vowels)
# vowels2 = [i (if i in 'aeiou') for i in alphabet]
# print('The vowels are', vowels2)
Comprehension can also be used to generate a dictionary. Create a dictionary using comprehension.
dict1 = {i: alphabet[i] for i in range(26)}
print('The last letter of the alphabet is', dict1[25], '.')