PCAP Comprehensions and Iterators 2 — Questions and Answers
Question 1: What does the `zip()` function do?
- Compresses files
- Combines multiple iterables element-by-element into tuples (Correct answer)
- Sorts two lists together
- Creates a zipped archive
Correct answer: Combines multiple iterables element-by-element into tuples
`zip()` pairs elements from multiple iterables into tuples, stopping at the shortest iterable.
Question 2: What is the `__iter__` method required for?
- Making an object callable
- Making an object iterable (Correct answer)
- Making an object printable
- Making an object comparable
Correct answer: Making an object iterable
The `__iter__` method makes an object iterable by returning an iterator object.
Question 3: What does `__next__` return when the iterator is exhausted?
- Returns None
- Raises StopIteration (Correct answer)
- Returns an empty list
- Raises IndexError
Correct answer: Raises StopIteration
When an iterator has no more items, `__next__` raises `StopIteration` to signal completion.
Question 4: What does `sorted()` return?
- The original list sorted in place
- A new sorted list (Correct answer)
- A sorted iterator
- A sorted tuple
Correct answer: A new sorted list
`sorted()` returns a new sorted list without modifying the original iterable.
Question 5: Which built-in function returns the sum of all elements in an iterable?
- total()
- add()
- sum() (Correct answer)
- reduce()
Correct answer: sum()
`sum(iterable)` returns the total of all numeric elements in the iterable.
Question 6: What does `reversed()` return?
- A reversed list
- A reverse iterator (Correct answer)
- A reversed string
- A sorted list in reverse
Correct answer: A reverse iterator
`reversed()` returns a reverse iterator, not a list — you need to convert it with `list()` for a list.
What does the `zip()` function do?