![]() |
VOOZH | about |
The zip() function in Python is used to combine two or more iterables (like lists, tuples, strings, dictionaries, etc.) into a single iterator of tuples.
Input: a = ["Liam", "Emma", "Noah"], b = [90, 85, 88]
Output: [("Liam", 90), ("Emma", 85), ("Noah", 88)]
Explanation: Elements at the same position from both iterables are grouped together into tuples.
[] [(1,), (2,), (3,)] [(1, 'a'), (2, 'b'), (3, 'c')]
Explanation:
When the iterables passed to zip() have unequal lengths, Python stops pairing as soon as the shortest iterable runs out of elements. This ensures that zip() never tries to access a missing value from a longer iterable.
[('Hiro', 88), ('Mila', 94)]
Explanation: The scores list has only two elements, so zip() forms only two pairs. The third name 'Tariq' is ignored because there is no matching score.
Unzipping is the reverse of zipping. If you already have a list of pairs, you can split them back into separate sequences using the * operator. This is helpful when you need to process values independently again.
Fruits: ('Apple', 'Banana', 'Orange')
Quantities: (10, 20, 30)
Explanation: * operator unpacks the list of tuples, allowing zip() to regroup the first elements together and the second elements together. As a result, we get one tuple of fruit names and one tuple of quantities.
zip() can also be used to pair dictionary keys and values. This is useful for converting a dictionary into a list of key-value tuples or when iterating over both parts together.
[('name', 'Felix'), ('age', 27), ('grade', 'A')]
Explanation: zip() pairs each key with its corresponding value, creating a clean list of (key, value) tuples. This representation is helpful for iteration, display, or converting the data into other formats.