Python3 zip() Function
Description
zip()The function takes iterable objects (such as lists, tuples, strings, etc.) as parameters, packs the corresponding elements in the objects into tuples one by one, and then returns an object composed of these tuples. The advantage of this is that it saves a lot of memory.
We can use list() conversion to output the list.
If the number of elements in each iterator is inconsistent, the returned list length 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 2.x, zip() returns a list.
If you need to understand the application in Python 2, you can refer toPython zip()。
Syntax
zip syntax:
zip([iterable, ...])
Parameter description:
- iterable -- Iterable object (such as lists, tuples, strings, etc.)
Return Value
Returns an object.
Examples
The following examples demonstrate how to use zip:
Examples (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 consistent with 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
>>> list(a1)
[1, 2, 3]
>>> list(a2)
[4, 5, 6]
>>>
Python3 Built-in Functions