โ† All Python Flashcard Decks

Python List Comprehensions and Generators Flashcards

6 cards from real Python practice questions. Tap to flip, then mark Knew It or Still Learning โ€” missed cards come back until you master them.

Read the first 6 Python List Comprehensions and Generators flashcards as text
  1. What is the output of `[x**2 for x in range(4)]`?

    Answer: [0, 1, 4, 9]

    range(4) produces 0, 1, 2, 3, and squaring each gives [0, 1, 4, 9].

  2. Which syntax creates a generator expression in Python?

    Answer: (x for x in range(10))

    Parentheses around a comprehension-style expression create a generator, not a list.

  3. What does the `yield` keyword do in a Python function?

    Answer: Pauses execution and returns a value to the caller, resuming on next call

    yield turns a function into a generator, pausing at each yield and resuming from that point when next() is called.

  4. What is the output of `list(x for x in range(5) if x % 2 == 0)`?

    Answer: [0, 2, 4]

    The condition x % 2 == 0 filters to even numbers 0, 2, and 4 from range(5).

  5. Which of the following creates a set comprehension?

    Answer: {x*2 for x in range(5)}

    Curly braces with a single expression and no colon create a set comprehension.

  6. What is the memory advantage of using a generator over a list?

    Answer: Generators produce values one at a time, using constant memory

    Generators yield values lazily one at a time, so they never hold the entire sequence in memory.