What is the difference between a list comprehension and a generator expression?
IntermediateConceptLanguage essentials & functions
Answer
A list comprehension [...] builds the whole list in memory immediately. A generator expression (...) yields one item at a time, on demand, and can only be iterated once.
total = sum(len(line) for line in open("access.log", encoding="utf-8"))
That processes a 20 GB log in constant memory. Use a list when you need indexing, len(), or multiple passes; use a generator for streaming and for feeding sum, any, all, max.
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner