0
0
Pythonprogramming~20 mins

zip() function in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Zip Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of zip with lists of different lengths
What is the output of this code?
list1 = [1, 2, 3, 4]
list2 = ['a', 'b']
result = list(zip(list1, list2))
print(result)
Python
list1 = [1, 2, 3, 4]
list2 = ['a', 'b']
result = list(zip(list1, list2))
print(result)
A[(1, 'a'), (2, 'b')]
B[(1, 'a'), (2, 'b'), (3, None), (4, None)]
C[(1, 'a'), (2, 'b'), (3, ''), (4, '')]
D[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
Attempts:
2 left
๐Ÿ’ก Hint
zip stops when the shortest input is exhausted.
โ“ Predict Output
intermediate
2:00remaining
Using zip with unpacking operator
What is the output of this code?
pairs = [(1, 'x'), (2, 'y'), (3, 'z')]
numbers, letters = zip(*pairs)
print(numbers)
print(letters)
Python
pairs = [(1, 'x'), (2, 'y'), (3, 'z')]
numbers, letters = zip(*pairs)
print(numbers)
print(letters)
A
(1, 2, 3)
('x', 'y', 'z')
B[(1, 2, 3), ('x', 'y', 'z')]
C[(1, 'x'), (2, 'y'), (3, 'z')]
DError: cannot unpack
Attempts:
2 left
๐Ÿ’ก Hint
The * operator unpacks the list of tuples into separate arguments for zip.
โ“ Predict Output
advanced
2:00remaining
Output of zip with generator expressions
What is the output of this code?
gen1 = (x*x for x in range(3))
gen2 = (x+1 for x in range(5))
result = list(zip(gen1, gen2))
print(result)
Python
gen1 = (x*x for x in range(3))
gen2 = (x+1 for x in range(5))
result = list(zip(gen1, gen2))
print(result)
AError: generators cannot be zipped
B[(0, 1), (1, 2), (4, 3), (9, 4), (16, 5)]
C[(0, 1), (1, 2), (4, 3)]
D[(0, 1), (1, 2)]
Attempts:
2 left
๐Ÿ’ก Hint
zip stops when the shortest generator is exhausted.
โ“ Predict Output
advanced
2:00remaining
Result of zipping dictionaries
What is the output of this code?
dict1 = {'a': 1, 'b': 2}
dict2 = {'x': 10, 'y': 20, 'z': 30}
result = list(zip(dict1, dict2))
print(result)
Python
dict1 = {'a': 1, 'b': 2}
dict2 = {'x': 10, 'y': 20, 'z': 30}
result = list(zip(dict1, dict2))
print(result)
A[('a', 1), ('b', 2), ('x', 10), ('y', 20), ('z', 30)]
B[('a', 'x'), ('b', 'y')]
C[('a', 'x'), ('b', 'y'), ('c', 'z')]
DError: cannot zip dictionaries
Attempts:
2 left
๐Ÿ’ก Hint
Iterating a dictionary yields its keys.
๐Ÿง  Conceptual
expert
3:00remaining
Behavior of zip with infinite iterator
Consider this code:
import itertools
infinite = itertools.count(1)
finite = [10, 20, 30]
result = list(zip(infinite, finite))
print(result)

What is the output?
AError: cannot zip infinite iterator
BInfinite loop, program never ends
C[(1, 10), (2, 20), (3, 30), (4, None)]
D[(1, 10), (2, 20), (3, 30)]
Attempts:
2 left
๐Ÿ’ก Hint
zip stops when the shortest input is exhausted, even if the other is infinite.