Tip 23 Eschew Comprehension Expressions, If Needed

Pythonic Programming — by Dmitry Zinoviev (32 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Find the “Missing” Switch | TOC | Use Slicing to Reverse and Split 👉

★★2.7, 3.4+ Comprehension expressions are great tools for transforming an iterable into another iterable (the outputs are limited to a list, dictionary, and set). That is what they do at the end of the day. Unfortunately, comprehension expressions have two limitations.

The first limitation is the requirement to apply an expression to each element of the original iterable. What if you want to apply more than one expression or use non-expression statements? Fortunately, this limitation is easy to bypass: create a one-parameter function that transforms an item in whatever way you want, and use that function in the expression.

​ ​def​ ​veryComplexFunction​(x):
​ ​return​ x

​ [veryComplexFunction(x) ​for​ x ​in​ iterable]

The second limitation is worse: the value of a comprehension expression is one iterable. How do you split the original iterable based on some condition and apply different transformations to each part? This operation is not possible unless you use two (or more) comprehension expressions:

​ result1 = [func1(x) ​for​ x ​in​ iterable ​if​     cond(x)]
​ result2 = [func2(x) ​for​ x ​in​ iterable ​if​ ​not​ cond(x)]

The solution is not elegant and quite expensive if computing the condition is not…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.