Skip to content

[Python] Introduction to the use of the zip() function

Last Updated on 2020-10-02 by Clay

python
Display Python code on the screen

Introduction

zip() is a function which can combine different iterable objects with the same index value into a tuple data type. It is very convenient when we need to combine different lists in Python. The following will look at a practical example.


zip() usage example

Just like the above, the zip() function can combine different lists and return the data type of tuple. At the beginning, zip() just return an object, we may have to use list() to convert the returned result of zip().

i = [1, 2, 3]
j = ['a', 'b', 'c']
print(zip(i, j))


Output:

<zip object at 0x00000181F7BF8148>

The returned iterable object can not see the real value, so we need to convert it.

print(list(zip(i, j)))


Output:

[(1, 'a'), (2, 'b'), (3, 'c')]

After using the list() conversion, we can see the returned tuple data. We can see that the two variables i and j we originally set, the same index values on both sides are combined together.

k = [12.0, 13.0, 14.0, 15.0]
print(list(zip(i, j, k)))


Output:

[(1, 'a', 12.0), (2, 'b', 13.0), (3, 'c', 14.0)]

The case of data of multiple List data types also applies, and multiple index values will be combined together. However we can see that the last item 15.0 of the k variable has no values to match, so it will not appear in the returned result.

This means that the combined result returned by zip() will only be based on the iterable object with the smallest length in the input, and values exceeding this length will not appear in the returned result.

In addition, the order of zip() input will affect the result of the combination.

print(list(zip(k, i, j)))


Output:

[(12.0, 1, 'a'), (13.0, 2, 'b'), (14.0, 3, 'c')]

So, the above is a note on how the zip() function is used in Python.


References


Read More

Tags:

Leave a Reply