Easy Tutorial
❮ Python Func Number Cos Python Att Dictionary Keys ❯

Python3 zip() Function

Python3 Built-in Functions


Description

The zip() function is used to take iterable objects as parameters, pair up the corresponding elements from each object into tuples, and then return an object consisting of these tuples. This approach saves memory.

We can use the list() function to convert the result into a list.

If the iterables have different lengths, the returned list will have the same length as the shortest iterable. Using the * operator, you can unpack the tuples back into lists.

>

The difference between zip in Python 2 and Python 3: In Python 2.x, zip() returns a list.

For information on Python2 applications, refer to Python zip().

Syntax

The syntax for zip is:

zip([iterable, ...])

Parameter explanations:

Return Value

Returns an object.

Examples

The following examples demonstrate the use of 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 list
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(a,c))          # Matches the length of the shortest list
[(1, 4), (2, 5), (3, 6)]

>>> a1, a2 = zip(*zip(a,b))      # Opposite of zip, `zip(*)` can be understood as unpacking, returning a matrix-like structure
>>> list(a1)
[1, 2, 3]
>>> list(a2)
[4, 5, 6]
>>>

Python3 Built-in Functions

❮ Python Func Number Cos Python Att Dictionary Keys ❯