Tip 20 Embrace Comprehensions

Pythonic Programming — by Dmitry Zinoviev (29 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Try It | TOC | Make Your Code Compact with Conditional Expressions 👉

★★2.7, 3.4+ In addition to the well-known list comprehension, Python has a flock of other comprehension expressions.

Set comprehension is enclosed in curly braces {} and acts almost like list comprehension, except that the result is a set with the duplicates removed. You could accomplish the same effect by applying set to list comprehension, but set comprehension is considerably faster:

​ {c ​for​ c ​in​ ​'Mary had a little lamb'​ ​if​ c ​in​ string.ascii_letters}​=> ​{'i', 'a', 'e', 'M', 'm', 'h', 't', 'b', 'y', 'd', 'r', 'l'}​

Remember that Python sets are not ordered. The order of printout is somewhat arbitrary and does not match the order of insertion into the set. The next related construct is dictionary comprehension. Naturally, it constructs a dictionary. It uses curly braces {} too and separates the new dictionary keys and values with a colon :. The following expression creates a dictionary of human-readable character positions as keys and their values, but only for the alphabetic characters:

​ {pos+1: c ​for​ pos, c ​in​ enumerate(s) ​if​ c ​in​ string.ascii_letters}​=> ​{1: 'M', 2: 'a', 3: 'r', 4: 'y', 6: 'h', 7: 'a', 8: 'd', 10: 'a', ...}​

--

--

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.