Chapter 5: List comprehension

List comprehension

face Josiah Wang

You may find yourself doing something like the following quite often. What does the code do?

capitals = ["London", "Paris", "Rome", "Madrid"] 
lengths = []
for capital in capitals:
    lengths.append(len(capital))

Python recommends using list comprehension for such cases to make it more compact and readable. It actually runs faster too!

lengths = [len(capital) for capital 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(word) <= 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(word) <= 4]

Here are some more complicated versions of list comprehensions. These are probably the furthest you should go with list comprehension. Anything more complicated will become quite hard to read!

[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]

The general guideline is that you should use list comprehensions when it makes your code more readable.