Python Control Flow: Loops 4 — Questions and Answers
Question 1: What does `zip([1,2,3], ['a','b'])` produce when iterated?
- (1,'a'), (2,'b'), (3, None)
- (1,'a'), (2,'b') (Correct answer)
- Raises a ValueError
- (1,'a','b'), (2,)
Correct answer: (1,'a'), (2,'b')
`zip()` stops at the shortest iterable, so only (1,'a') and (2,'b') are produced.
Question 2: What is a list comprehension equivalent to `for x in range(5): result.append(x**2)`?
- `[x**2 for x in range(5)]` (Correct answer)
- `(x**2 for x in range(5))`
- `{x**2 for x in range(5)}`
- `list(x**2 in range(5))`
Correct answer: `[x**2 for x in range(5)]`
A list comprehension with square brackets `[expr for var in iterable]` produces a list.
Question 3: Which of the following correctly uses `while` with an `else` clause?
- `while x > 0: x -= 1 else: print('done')`
- `while x > 0: x -= 1 else: print('done')` (Correct answer)
- `while x > 0: x -= 1 elif: print('done')`
- `while x > 0: x -= 1 finally: print('done')`
Correct answer: `while x > 0: x -= 1 else: print('done')`
The `else` clause is at the same indentation level as `while`, not inside the loop body.
Question 4: How many times does this loop print? ``` for _ in range(3): for _ in range(2): print('x') ```
- 2
- 3
- 5
- 6 (Correct answer)
Correct answer: 6
The inner loop prints 2 times per outer iteration, and the outer runs 3 times: 3×2 = 6.
Question 5: What does `range(5, 5)` produce?
- [5]
- [5, 5]
- An empty range (Correct answer)
- Raises ValueError
Correct answer: An empty range
When start equals stop, `range()` produces no values — it's an empty sequence.
Question 6: What is the output of: ``` x = [1, 2, 3] for i in x: x.append(i) if len(x) > 5: break print(len(x)) ```
- 3
- 5
- 6 (Correct answer)
- Infinite loop
Correct answer: 6
The loop appends until len(x) > 5, so it stops when len is 6 (after adding two elements).
Question 7: Which built-in function returns an iterator that applies a function to every item of an iterable?
- `filter()`
- `reduce()`
- `map()` (Correct answer)
- `zip()`
Correct answer: `map()`
`map(func, iterable)` applies `func` to each element and returns an iterator of results.
What does `zip([1,2,3], ['a','b'])` produce when iterated?