List comprehensions
You may find yourself doing something like the below quite often. What does the code do?
capitals = ["London", "Paris", "Rome", "Madrid"]
lengths = []
for c in capitals:
lengths.append(len(c))
Python recommends using list comprehension for such cases to make it more compact and readable.
lengths = ([len(c) for c in capitals])
Here’s another example. (What does it do?)
words = ["this", "list", "contains", "extremely", "lengthy", "expressions"]
short_words = []
for word in words:
if len(words) <= 4:
short_words.append(word)
The version using list comprehension is much more compact (and perhaps even easier to read).
short_words = [word for word in words if len(words) <= 4]
Here are some more complicated versions of list comprehensions:
[expr for var in list_name]
[expr for var in list_name if condition]
[expr for var1 in list_name1 for var2 in list_name2]
[expr for var in list_name if condition1 if condition2]
[expr if condition else condition for var in list_name]
The general guideline is that you should use list comprehensions when it makes your code more readable.
Set and dictionary comprehension
Comprehension can also be applied to sets…
elements = [1, 2, 4, 2, 3, 2]
unique_elements = {element for element in elements}
…and to dictionaries.
tall_students = {key: value for (key, value) in height_dict.items() if value > 5}