Comprehensions — Lists, Dicts, Sets & Generator Expressions — Concept Check
Questions on Comprehensions — Lists, Dicts, Sets & Generator Expressions. Comprehensions build collections declaratively — [x*2 for x in nums if x > 0] — replacing 4-line loops with one readable line, with dict/set variants and lazy generator expressions.
Questions in this quiz
8 questions on Comprehensions — Lists, Dicts, Sets & Generator Expressions — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.Given the list `nums = [3, -1, 8, -5, 12]`, what does the comprehension `[n * 2 for n in nums if n > 0]` produce?
- A[6, -2, 16, -10, 24]
- B[3, -1, 8, -5, 12]
- C[3, 8, 12]
- D[6, 16, 24]
2.A developer uses `{n: n * n for n in range(5)}`. What is the result?
- AA set of squares from 0 to 4
- BA generator producing squares from 0 to 4
- CA dictionary with keys 0 to 4 and their squares as values
- DA list of squares from 0 to 4
3.You need to process a large file line by line to count characters in lines longer than 80 characters. Which approach is most memory-efficient?
- AUsing a dictionary comprehension
- BReading the entire file into a list
- CUsing a list comprehension
- DUsing a generator expression
4.What is the output of `print(any(n > 40 for n in [4, 8, 15, 16, 23, 42]))`?
- ATrue
- BFalse
- C[42]
- DNone
5.Which of the following is a key advantage of using generator expressions over list comprehensions?
- AThey produce results in sorted order
- BThey use constant memory
- CThey are faster in execution
- DThey are easier to read
6.What happens when you try to iterate over a generator twice?
- AIt starts from the beginning again
- BIt produces items in reverse order
- CIt raises an exception
- DThe second iteration produces no items
7.A developer writes `[n for n in nums if n % 2 == 0]` to filter even numbers. What common mistake might they make if they expect this to modify `nums`?
- AAssuming it returns a generator
- BBelieving it filters out odd numbers from `nums`
- CThinking it raises an error if no evens are found
- DExpecting `nums` to be modified in place
8.Which statement about comprehensions is true?
- AThey can include an if/else before the for loop
- BThey are always faster than loops
- CThey can replace complex, multi-paragraph loops
- DThey can only be used with lists