This quiz question examines your understanding of iterators and generators in Python.
It focuses on creating and using generators to produce a sequence of values.
You should be able to distinguish between list comprehensions and generator expressions and understand their usage.
Contents
Question: Iterators and Generators
Consider the following list comprehension and generator expression, which both generate the square of each number in the list numbers
:
numbers = [1, 2, 3, 4, 5]
list_comprehension = [n**2 for n in numbers]
generator_expression = (n**2 for n in numbers)
Which of the following statements about list_comprehension
and generator_expression
is true?
Option B is the correct answer.
- Explanation: This option correctly explains the key difference between a list comprehension and a generator expression.
- The list comprehension evaluates all elements immediately and stores them in memory, while the generator expression evaluates each element only when iterated over, using less memory and allowing for potentially infinite sequences.
- Result:
list_comprehension = [1, 4, 9, 16, 25]
(fully evaluated list);generator_expression
is an iterator that yields values lazily.