Home >Backend Development >Python Tutorial >What is zip function in python?
What is zip function in python?
The zip() function in python is used to take an iterable object as a parameter, pack the corresponding elements in the object into tuples, and then return an object composed of these tuples. The advantage of this is that it saves a lot of memory.
If the number of elements of each iterator is inconsistent, the length of the returned list is the same as the shortest object
Related recommendations: "Python Tutorial"
Syntax
zip([iterable, ...])
Parameters: iterable is one or more iterators
Return value: An object is returned, and list() conversion can be used to output a list
1. Example 1
>>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> zip(a, b) <zip object at 0x0000000003BB4188> >>> list(zip(a, b)) [(1, 4), (2, 5), (3, 6)] >>> >>> >>> c = [4, 5, 6, 7, 8] >>> list(zip(a, c)) [(1, 4), (2, 5), (3, 6)] >>>
2. Example 2
Two lists of equal length are merged into a dictionary: keys = ["A", "B", "C"], values = ["1", "2", "3"], requirement: merge into {"A":1, "B":2, "C" :3}, please use one line of code to implement the
idea: first use the zip() function to pack the two lists into a tuple object, and then use dict to construct the dictionary, so the code is
print(dict(zip(keys, values)))
Run result:
{'B': '2', 'A': '1', 'C': '3'}
The above is the detailed content of What is zip function in python?. For more information, please follow other related articles on the PHP Chinese website!