Hackerrank Comprehensions (List, Dict, Set, and Generator Expressions) — Questions and Answers
Question 1: What does the following list comprehension produce? python [x**2 for x in range(5) if x % 2 == 0]
- [0, 4, 16] (Correct answer)
- [0, 1, 4, 9, 16]
- [4, 16]
- [0, 4, 8, 16]
Correct answer: [0, 4, 16]
range(5) gives 0,1,2,3,4. The condition x%2==0 keeps even numbers: 0,2,4. Squaring them: 0**2=0, 2**2=4, 4**2=16 → [0, 4, 16].
Question 2: Which of the following creates a dictionary mapping each word to its length from a list? python words = ['cat', 'elephant', 'ox']
- {w: len(w) for w in words} (Correct answer)
- {len(w): w for w in words}
- [w: len(w) for w in words]
- {w, len(w) for w in words}
Correct answer: {w: len(w) for w in words}
A dict comprehension uses curly braces with a key:value expression. {w: len(w) for w in words} maps each word string to its integer length, producing {'cat': 3, 'elephant': 8, 'ox': 2}.
Question 3: What is the type and value of the following expression? python result = (x*2 for x in range(3))
- A generator object yielding 0, 2, 4 (Correct answer)
- The list [0, 2, 4]
- The tuple (0, 2, 4)
- A set {0, 2, 4}
Correct answer: A generator object yielding 0, 2, 4
Parentheses with a comprehension-style expression create a generator expression, not a tuple. The result is a generator object that lazily yields 0, 2, 4 when iterated. To get a tuple you'd need tuple(x*2 for x in range(3)).
Question 4: What does the following set comprehension produce? python {len(w) for w in ['hi', 'bye', 'no', 'yes']}
- {2, 3} (Correct answer)
- {2, 3, 2, 3}
- [2, 3, 2, 3]
- {2, 2, 3, 3}
Correct answer: {2, 3}
The lengths are: 'hi'→2, 'bye'→3, 'no'→2, 'yes'→3. A set comprehension automatically deduplicates, resulting in {2, 3}.
Question 5: How do you flatten a 2D list [[1,2],[3,4],[5,6]] into [1,2,3,4,5,6] using a list comprehension?
- [x for row in [[1,2],[3,4],[5,6]] for x in row] (Correct answer)
- [x for x in row for row in [[1,2],[3,4],[5,6]]]
- [[x for x in row] for row in [[1,2],[3,4],[5,6]]]
- [row for x in [[1,2],[3,4],[5,6]] for row in x]
Correct answer: [x for row in [[1,2],[3,4],[5,6]] for x in row]
Nested comprehensions iterate outer-to-inner left-to-right: first 'for row in matrix' selects each sublist, then 'for x in row' iterates its elements, yielding a flat list.
Question 6: Which comprehension correctly inverts a dictionary {'a':1, 'b':2, 'c':3} so values become keys?
- {v: k for k, v in {'a':1,'b':2,'c':3}.items()} (Correct answer)
- {k: v for v, k in {'a':1,'b':2,'c':3}.items()}
- [v, k for k, v in {'a':1,'b':2,'c':3}.items()]
- {v for k, v in {'a':1,'b':2,'c':3}.items()}
Correct answer: {v: k for k, v in {'a':1,'b':2,'c':3}.items()}
.items() yields (key, value) pairs. Unpacking as k, v and writing v: k in the dict comprehension swaps them, giving {1:'a', 2:'b', 3:'c'}.
What does the following list comprehension produce?
python
[x**2 for x in range(5) if x % 2 == 0]