Comprehensions (List, Dict, Set, and Generator Expressions) Flashcards
6 cards from real HACKERRANK practice questions. Tap to flip, then mark Knew It or Still Learning — missed cards come back until you master them.
Read the first 6 Comprehensions (List, Dict, Set, and Generator Expressions) flashcards as text
What does the following list comprehension produce? python [x**2 for x in range(5) if x % 2 == 0]
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].
Which of the following creates a dictionary mapping each word to its length from a list? python words = ['cat', 'elephant', 'ox']
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}.
What is the type and value of the following expression? python result = (x*2 for x in range(3))
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)).
What does the following set comprehension produce? python {len(w) for w in ['hi', 'bye', 'no', 'yes']}
Answer: {2, 3}
The lengths are: 'hi'→2, 'bye'→3, 'no'→2, 'yes'→3. A set comprehension automatically deduplicates, resulting in {2, 3}.
How do you flatten a 2D list [[1,2],[3,4],[5,6]] into [1,2,3,4,5,6] using a list comprehension?
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.
Which comprehension correctly inverts a dictionary {'a':1, 'b':2, 'c':3} so values become keys?
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'}.