Using if in a comprehension

In the previous chapter, we discussed comprehensions, one-liner code expressions, which usually create iterable objects from one or a few other iterables. They do support the if condition as well. For example, the following comprehension loops over a list of dictionaries, and returns a list of character names, one per dictionary in the first list, if the surname of the corresponding character is equal to Rabbit:

>>> characters = [
{'name': 'Peter', "surname": 'Rabbit'},
{'name': 'Josephine', 'surname': 'Rabbit'},
{'name': 'Michael', 'surname': 'McGregor'}
]

>>> rabbits = [el['name'] for el in characters if el['surname'] == 'Rabbit']
>>> rabbits
['Peter', 'Josephine']

Using comprehensions with if is a great practice; most of the time, comprehensions are very expressive and easy to grasp, while short and performant—a rare win-win scenario.

One-liners are great, but they can't completely replace loops. Besides, there are different types of loops, and some are quite different from the one-liners in terms of what they do. Let's take a look.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.65.247