Computer Science Grade 9 20 min

Generator Expressions: Concise Generator Creation

Create generators using generator expressions for even more concise code.

Tutorial Preview

1

Introduction & Learning Objectives

Learning Objectives Define what a generator expression is and explain its purpose. Differentiate between a generator expression and a list comprehension based on syntax and memory usage. Write the correct syntax for a basic generator expression to produce a sequence of values. Incorporate a conditional `if` clause into a generator expression to filter data. Iterate over a generator object using a `for` loop to access its values. Explain the concept of 'lazy evaluation' and why it makes generator expressions memory-efficient. Use built-in functions like `sum()` or `list()` to consume a generator. Ever tried to create a list with a million numbers and watched your computer slow to a crawl? 🐢 What if you could work with that huge sequence one number at a time, inst...
2

Key Concepts & Vocabulary

TermDefinitionExample GeneratorAn object that acts like an iterator, producing a sequence of values one at a time when requested, rather than all at once.A generator for the numbers 1, 2, 3 would give you '1', then '2', then '3', but it never holds all three numbers in memory at the same time. Generator ExpressionA short, concise syntax for creating a generator. It looks very similar to a list comprehension but uses parentheses instead of square brackets.`(x * 2 for x in range(5))` creates a generator that will yield 0, 2, 4, 6, 8. Lazy EvaluationThe strategy of delaying a calculation until its result is actually needed. Generators use this, producing values only when you ask for the next one.The expression `(num for num in range(1000000))` doesn't calcu...
3

Core Syntax & Patterns

Basic Generator Expression Syntax (expression for item in iterable) This is the fundamental pattern. It consists of an expression to be evaluated, a `for` clause to loop over an iterable (like a list or range), all wrapped in parentheses `()`. Generator Expression with a Condition (expression for item in iterable if condition) This pattern adds a filter. The `expression` is only evaluated for items in the `iterable` where the `condition` is true. This lets you select specific data on the fly. Single-Use Consumption A generator can only be iterated over once. Once a `for` loop or function like `sum()` has gone through all the items in a generator, it is exhausted (empty). If you need to use the sequence again, you must create a new generator expression.

4 more steps in this tutorial

Sign up free to access the complete tutorial with worked examples and practice.

Sign Up Free to Continue

Sample Practice Questions

Challenging
What is the output of the following code? g = (x for x in range(10)) next(g) next(g) print(sum(g))
A.45
B.42
C.44
D.55
Challenging
You have a sentence `s = 'the quick brown fox jumps over the lazy dog'`. Which one-line expression correctly finds the length of the longest word that contains the letter 'o'?
A.len(word for word in s.split() if 'o' in word)
B.max(len(word) for word in s.split() if 'o' in word)
C.max(word for word in s.split() if 'o' in word)
D.sum(len(word) for word in s.split() if 'o' in word)
Challenging
Analyze the expression `sum(x*x for x in range(1, 4))`. Which statement best describes how 'lazy evaluation' works here?
A.list `[1, 4, 9]` is created first, and then `sum()` is called on that list.
B.The `sum()` function receives the generator object. It requests one value at a time (1*1=1), adds it to a running total, requests the next (2*2=4), adds it, and so on, without ever storing all the squared numbers at once.
C.The generator calculates all squares `1, 4, 9` and holds them, then passes them to `sum()` one by one.
D.The `range(1, 4)` is fully expanded into a list, then the generator squares each number, then `sum()` adds them.

Want to practice and check your answers?

Sign up to access all questions with instant feedback, explanations, and progress tracking.

Start Practicing Free

More from Advanced Python Techniques: Beyond the Basics

Ready to find your learning gaps?

Take a free diagnostic test and get a personalized learning plan in minutes.