Practice: Zip
Q1. Pair two lists
Print the list of pairs made from [1, 2, 3] and ['one', 'two', 'three'].
Goal: Create pairs with zip.
Q2. Name and age
Print 'Ann is 21' and 'Raj is 25' from the two lists ['Ann', 'Raj'] and [21, 25].
Goal: Loop over two lists.
Q3. Build a dictionary
Make a dictionary from keys ['a', 'b', 'c'] and values [1, 2, 3] and print it.
Goal: Create a dictionary.
Q4. Add pairwise
Print a new list with the sums of matching items of [1, 2, 3] and [4, 5, 6].
Goal: Combine zip and a comprehension.
Q5. Dot product
Compute and print the dot product of [1, 2, 3] and [4, 5, 6].
Goal: Use zip inside sum.
Q6. Unzip pairs
Split [(1, 'a'), (2, 'b')] into a tuple of numbers and a tuple of letters and print both.
Goal: Unzip with *.
Q7. Transpose a table
Transpose [[1, 2], [3, 4], [5, 6]] so the rows become columns and print the list of lists.
Goal: Transpose with zip.
Q8. Count increases
Count how many times the next value is larger than the previous one in [3, 5, 4, 8, 9].
Goal: Compare neighbours.
Q9. Shortest wins
What does this program print?
print(list(zip([1, 2, 3], "ab")))Goal: Know the length rule.
Q10. Zip of three
What does this program print?
print(list(zip("ab", "cd", "ef")))Goal: Zip several iterables.
Q11. Used-up zip
What does this program print?
z = zip([1], [2])
print(len(list(z)))
print(len(list(z)))Goal: Remember one-use iterators.
Q12. zip_longest fill
What does this program print?
from itertools import zip_longest
print(list(zip_longest([1, 2, 3], ["a"], fillvalue="-")))Goal: Use zip_longest.
Q13. Dictionary from zip
What does this program print?
d = dict(zip("abc", [10, 20]))
print(d)Goal: Predict a dictionary.
Q14. Strict mode
What does this program print?
try:
list(zip([1, 2], [3], strict=True))
except ValueError:
print("error")
else:
print("ok")Goal: Understand strict.
Q15. Wrong zip result
The program prints a zip object description instead of the pairs. Fix it.
a = [1, 2]
b = [3, 4]
print(zip(a, b))Goal: Convert zip to a list.
Q16. Missing star
This raises a ValueError because zip(pairs) gives only one group. Fix it to unzip the pairs.
pairs = [(1, "a"), (2, "b")]
nums, chars = zip(pairs)
print(nums)Goal: Use the star operator.
Q17. Lists of unequal size
What happens if you zip a list of 5 items with a list of 3 items, and how can you avoid losing data?
Goal: Explain zip length rules.
Q18. zip versus enumerate
Explain the difference between zip and enumerate in one or two sentences.
Goal: Contrast zip and enumerate.
Q19. Grade report
For names ['Asha', 'Ben'] and marks [82, 45], print each name with pass if the mark is at least 50, otherwise fail.
Goal: Process parallel data.
Q20. Differences in readings
Print the change between each pair of consecutive readings in [100, 103, 101, 108].
Goal: Compute consecutive differences.