Python3 zip() Function
Description
zip() The function takes iterables (such as lists, tuples and strings) as arguments, packs the corresponding elements into tuples, and returns an object made up of those tuples, which saves a considerable amount of memory.
We can use list() to convert it and output a list.
If the iterables have different lengths, the returned list has the same length as the shortest one; the * operator can be used to unpack the tuples back into lists.
Difference between zip in Python 2 and Python 3: in Python 2.x, zip() returned a list.
For Python 2 usage, refer to Python zip()。
Syntax
zip syntax:
zip([iterable, ...])
Parameter Description:
- iterable -- an iterable (such as a list, tuple or string)
Return Value
Returns an object.
Example
The following example shows how to use zip:
Example (Python 3.0+)
a
=
[
1
,
2
,
3
]
b
=
[
4
,
5
,
6
]
c
=
[
4
,
5
,
6
,
7
,
8
]
zipped
=
zip
(
a
,
b
)
Returns an object
zipped
<
zip
object
at
0x103abc288
list
(
zipped
)
Convert to a list with list()
[
(
1
,
4
)
,
(
2
,
5
)
,
(
3
,
6
)
]
list
(
zip
(
a
,
c
)
)
The number of elements matches the shortest list
[
(
1
,
4
)
,
(
2
,
5
)
,
(
3
,
6
)
]
a1
,
a2
=
zip
(
zip
(
a
,
b
)
)
The opposite of zip, zip(*) can be understood as unpacking, returning a two-dimensional matrix form
list
(
a1
)
[
1
,
2
,
3
]
list
(
a2
)
[
4
,
5
,
6
]
Python3 built-in function