PyPython · Lesson 11 of 14
Comprehensions & Generators
List comprehensions are Pythonic. They are also extremely easy to abuse until you have written a one-liner that takes 10 minutes to understand. Use them for simple transformations; reach for a loop when it gets complicated.
◆ Note
Generator expressions use O(1) memory regardless of input size. Prefer them over list comprehensions when you only need to iterate once and do not need random access. sum(x**2 for x in range(1_000_000)) is faster and uses less memory than sum([x**2 for x in range(1_000_000)]).
Generator expressions use O(1) memory regardless of input size. Prefer them over list comprehensions when you only need to iterate once and do not need random access. sum(x**2 for x in range(1_000_000)) is faster and uses less memory than sum([x**2 for x in range(1_000_000)]).