Python zip() function examples
( 48 Articles)
This article is about the zip() function in Python 3. We’ll cover the fundamentals then walk through a few practical examples.
zip() is a built-in function of Python that works like a zipper. It can take zero, one, or many iterables (lists, tuples, dictionaries, etc), aggregates them in a tuple, and return an iterator of tuples with each tuple having elements from all the iterables.
To unzip a Python object (for example, a list of tuples), we can also use the zip() function (there is no unzip() function in Python) with the * operator, like this:
The program below will zip the names of the people, emails, and phone numbers respectively.
names = ['A', 'B', 'C'] emails = ['[email protected]', '[email protected]', '[email protected]'] phone_numbers = [111, 222, 333] result = zip(names, emails, phone_numbers) print(list(result))
[('A', '[email protected]', 111), ('B', '[email protected]', 222), ('C', '[email protected]', 333)]
This example using the zip() function to unzip things.
number_letter_pairs = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')] numbers, letters = zip(*number_letter_pairs) print('Numbers', numbers) print('Letters', letters)
Numbers (1, 2, 3, 4, 5) Letters ('a', 'b', 'c', 'd', 'e')
This example demonstrates how zip() behaves when the input iterables have different numbers of elements.
numbers = [1, 2, 3] letters = ['A', 'B', 'C', 'D'] result = zip(numbers, letters) print(list(result))
[(1, 'A'), (2, 'B'), (3, 'C')]
This article has covered the basics and walked you through 3 examples of the zip() function. If you want to learn more things in Python, check out the following articles:
- Python reduce() function examples
- Python filter() function examples
- Examples of using map() function in Python 3
- Examples of numpy.linspace() in Python
- Python 3: Simultaneously Iterating over Multiple Sequences
- Python 3: Formatting a DateTime Object as a String
You can also take a glance at our Python topic page for more tutorials and examples.