Interview Prep/Python for DevOps/Language essentials & functions

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.

All Python for DevOps questions Roadmap: Python for automation

More on Language essentials & functions