PCAP Comprehensions and Iterators 1 — Questions and Answers
Question 1: Which syntax creates a list comprehension in Python?
- {x for x in range(5)}
- [x for x in range(5)] (Correct answer)
- (x for x in range(5))
- <x for x in range(5)>
Correct answer: [x for x in range(5)]
List comprehensions use square brackets: `[expression for item in iterable]`.
Question 2: What does a generator expression return compared to a list comprehension?
- A list evaluated immediately
- A lazy iterator evaluated on demand (Correct answer)
- A tuple
- A set
Correct answer: A lazy iterator evaluated on demand
A generator expression (using parentheses) returns an iterator that yields values lazily, using less memory.
Question 3: What is the result of `[x**2 for x in range(4)]`?
- [1, 4, 9, 16]
- [0, 1, 4, 9] (Correct answer)
- [0, 1, 2, 3]
- [1, 2, 3, 4]
Correct answer: [0, 1, 4, 9]
`range(4)` produces 0,1,2,3 and squaring each gives [0, 1, 4, 9].
Question 4: How do you add a condition to a list comprehension to include only even numbers?
- [x for x in range(10) if x%2==0] (Correct answer)
- [x if x%2==0 for x in range(10)]
- [x for x%2==0 in range(10)]
- [x for x in range(10) where x%2==0]
Correct answer: [x for x in range(10) if x%2==0]
A conditional list comprehension uses `if condition` at the end: `[x for x in iterable if condition]`.
Question 5: Which syntax creates a dictionary comprehension?
- [k:v for k,v in items]
- {k:v for k,v in items} (Correct answer)
- (k:v for k,v in items)
- dict(k:v for k,v in items)
Correct answer: {k:v for k,v in items}
Dictionary comprehensions use `{key: value for ...}` syntax with curly braces and a colon.
Question 6: What does the `enumerate()` function return when iterating?
- Only the index
- Only the value
- A tuple of (index, value) (Correct answer)
- A dictionary
Correct answer: A tuple of (index, value)
`enumerate()` yields `(index, value)` tuples for each item in the iterable.
Which syntax creates a list comprehension in Python?