The zip() function in Python can be used to combine objects of different types or sequences of equal length into a single iterable object. The resulting object contains tuples, where the i-th tuple contains the i-th element from each of the input sequences. Here are some examples of how to use zip() to combine objects:
a = [1, 2, 3]b = ['a', 'b', 'c']c = list(zip(a, b))print(c)# Output: [(1, 'a'), (2, 'b'), (3, 'c')] |
x = 'hello'y = 'world'z = list(zip(x, y))print(z)# Output: [('h', 'w'), ('e', 'o'), ('l', 'r'), ('l', 'l'), ('o', 'd')] |
a = [{'x': 1, 'y': 2}, {'x': 3, 'y': 4}]b = [{'z': 5}, {'z': 6}]c = [dict(list(x.items()) + list(y.items())) for x, y in zip(a, b)]print(c)# Output: [{'x': 1, 'y': 2, 'z': 5}, {'x': 3, 'y': 4, 'z': 6}] |
In the third example, we first use zip() to combine the two lists of dictionaries into a single iterable object containing tuples. Then, for each tuple, we use items() to get a list of key-value pairs for each dictionary, and concatenate them using the + operator. Finally, we use dict() to create a new dictionary from the concatenated list of key-value pairs.
zip() is a powerful function for combining objects in Python, and it can be used in many different ways depending on the types of objects you are working with.