Python zip() FunctionPython zip() function returns a zip object, which maps a similar index of multiple containers. It takes iterables (can be zero or more), makes it an iterator that aggregates the elements based on iterables passed, and returns an iterator of tuples. Python's zip() function is a built-in function that is used to combine two or more iterables into a single iterable. This function takes in any number of iterables (lists, tuples, sets, etc.) as arguments and returns an iterator that aggregates elements from each of the iterables into tuples. Each tuple contains the i-th element from each of the input iterables. The syntax for using the zip() function is: Parametersiterator1, iterator2, iterator3: These are iterator objects that joined together. ReturnIt returns an iterator from two or more iterators. Python zip() Function Example 1The below example shows the working of zip(). Output: [] {(5, 'five'), (4, 'four'), (6, 'six')} Explanation: In the above example, we have initialized the lists, i.e., numList (contains integer values) and strList (contains string values) and map the values by using zip(). In the first case, it converts iterator to a list and prints resultList that contains no values. Then, two iterables are passed in the zip(), i.e., numList, strList and convert iterator to set and return its values. Python zip() Function Example 2The below example unzip the values using zip(). Output: [('x', 6), ('y', 2), ('z', 8)] c = ('x', 'y', 'z') v = (6, 2, 8) The function takes in any number of iterables as arguments, separated by commas, and returns an iterator that generates tuples containing elements from each of the iterables. Example 3: Output: Alice 25 Bob 30 Charlie 35 We can also use the zip() function with more than two iterables. For example, suppose we have three lists: Example 4: Output: Alice 25 160 Bob 30 175 Charlie 35 180 In summary, the zip() function in Python is a powerful tool that allows us to combine two or more iterables into a single iterable. It is a useful function for working with data that is spread across multiple lists or other data structures. Next TopicPython Built in Functions |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India