Lesson 9
No Object is an Island
Chapter 5: List comprehension
Set and dict comprehension
Comprehension can also be applied to sets.
>>> tokens = ["feelings", "feelings", "like", "i've", "never", "lost", "you",
... "and", "feelings", "like", "i've", "never", "have", "you"]
>>> unique_short_words = {token for token in tokens if len(token) <= 4}
>>> print(unique_short_words)
{'and', 'like', 'you', "i've", 'have', 'lost'}
Comprehension can also be applied to dictionaries.
>>> heights = {"Josiah": 160, "Harry": 170, "Joe": 175, "William": 165}
>>> tall_students = {key: value for (key, value) in heights.items() if value >= 170}
>>> print(tall_students)
{'Harry': 170, 'Joe': 175}