Practice mode Python

Which of these expressions creates a generator object rather than a list?

Correct answer A. (x * 2 for x in range(5))

Explanation

Wrapping a comprehension in parentheses creates a generator expression, which yields values lazily one at a time. Square brackets build a full list, braces build a set, and passing a generator to list() consumes it into a list. Generators save memory for large or infinite sequences.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.