
#Python list comprehension generator#
So in addition to the “can I copy-paste my way from a loop to a comprehension” check, there’s another, fuzzier, check to consider: could your code be enhanced by a generator expression combined with an iterable-accepting function or class?Īny function or class that accepts an iterable as an argument might be a good candidate for combining with a generator expression. Sometimes all a comprehension needs to be more readable is better spacing.ĭef sum_of_squares ( numbers ): return sum ( n ** 2 for n in numbers ) If you’re unfamiliar with comprehensions, I recommend reading this article or watching this talk (the talk dives into generator expressions a bit more deeply).Ĭritics of list comprehensions often say they’re hard to read.Īnd they’re right, many comprehensions are hard to read. Note: In this article, I’ll be using the term “comprehension” to refer to all forms of comprehensions (list, set, dict) as well as generator expressions. This article isn’t meant to scare you off from comprehensions if you’re not already a fan it’s meant to encourage moderation for those of us (myself included) who need it.

We’re going to walk through a number of cases where there’s a more readable alternative to comprehensions and we’ll also see some not-so-obvious cases where comprehensions aren’t needed at all. This article is all about cases when comprehensions aren’t the best tool for the job, at least in terms of readability. While I love list comprehensions, I’ve found that once new Pythonistas start to really appreciate comprehensions they tend to use them everywhere.Ĭomprehensions are lovely, but they can easily be overused! I love list comprehensions so much that I’ve written an article about them, done a talk about them, and held a 3 hour comprehensions tutorial at P圜on 2018.


List comprehensions are one of my favorite features in Python.
