Python zip() Function
Description
zip()The function takes iterable objects as parameters, packs the corresponding elements in the objects into tuples one by one, and then returns a list composed of these tuples.
If the number of elements in each iterator is inconsistent, the length of the returned list is the same as the shortest object. Using the * operator, tuples can be unpacked into lists.
The difference between the zip method in Python 2 and Python 3: In Python 3.x, to reduce memory usage, zip() returns an object. To display a list, you need to manually convert it with list().
If you need to understand the application of Python 3, you can refer toPython3 zip()。
Syntax
zip syntax:
zip([iterable, ...])
Parameter description:
- iterable -- one or more iterators;
Return Value
Returns a list of tuples.
Examples
The following two examples respectively demonstratePython2.xandPython3.x zipthe usage of:
Example (Python 2.0+)
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # Pack into a list of tuples
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # The number of elements is the same as the shortest list
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # Contrary to zip, *zipped can be understood as unpacking, returning a two-dimensional matrix format
[(1, 2, 3), (4, 5, 6)]
Example (Python 3.0+)
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # Returns an object
>>> zipped
<zip object at 0x103abc288>
>>> list(zipped) # list() converts to a list
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(a,c)) # The number of elements is the same as the shortest list
[(1, 4), (2, 5), (3, 6)]
>>> a1, a2 = zip(*zip(a,b)) # Contrary to zip, zip(*) can be understood as unpacking, returning a two-dimensional matrix format
>>> list(a1)
[1, 2, 3]
>>> list(a2)
[4, 5, 6]
>>>
Python Built-in Functions