0
0
Pythonprogramming~5 mins

zip() function in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the zip() function do in Python?
The zip() function takes multiple sequences (like lists or tuples) and pairs their elements together into tuples, creating an iterator of these pairs.
Click to reveal answer
beginner
How does zip() handle sequences of different lengths?
It stops creating pairs when the shortest input sequence is exhausted, so the output length matches the shortest input.
Click to reveal answer
beginner
How can you convert the result of zip() into a list?
You can wrap zip() with list(), like list(zip(seq1, seq2)), to get a list of tuples.
Click to reveal answer
beginner
What will be the output of list(zip([1, 2], ['a', 'b'], [True, False]))?
The output will be [(1, 'a', True), (2, 'b', False)]. Each tuple contains elements from each list at the same position.
Click to reveal answer
intermediate
Can zip() be used to unzip a list of tuples? How?
Yes! Using the unpacking operator *, like zip(*zipped_list), you can separate paired elements back into individual sequences.
Click to reveal answer
What does zip([1, 2, 3], ['a', 'b', 'c']) return when converted to a list?
A[(1, 'a'), (2, 'b'), (3, 'c')]
B[(1, 2, 3), ('a', 'b', 'c')]
C[(1, 'a', 2), ('b', 3, 'c')]
D[(1, 'a'), (2, 'b')]
If you zip lists of different lengths, what happens?
AIt raises an error.
BIt ignores the shortest list.
CIt pairs elements until the longest list ends, filling missing values with None.
DIt pairs elements until the shortest list ends.
How do you unzip a list of tuples zipped = [(1, 'a'), (2, 'b')]?
A<code>zip(*zipped)</code>
B<code>unzip(zipped)</code>
C<code>zip(zipped*)</code>
D<code>list(zip(zipped))</code>
What type does zip() return?
AList
BIterator
CTuple
DDictionary
Which of these is a correct way to pair elements from two lists a and b?
A<code>zip(a * b)</code>
B<code>zip(a + b)</code>
C<code>zip(a, b)</code>
D<code>zip(a - b)</code>
Explain how the zip() function works and give an example with two lists.
Think about matching socks from two drawers.
You got /3 concepts.
    Describe how to unzip a list of tuples created by zip().
    Imagine separating pairs back into individual items.
    You got /3 concepts.