Python built-in Method - zip()

The zip() function is a built-in function in Python that returns an iterator that aggregates elements from two or more iterables (lists, tuples, etc.) into tuples.

Here's the syntax for the zip() function:

zip(*iterables)
Sourc‮w:e‬ww.theitroad.com

The zip() function takes any number of iterables as arguments and returns an iterator of tuples where the i-th tuple contains the i-th element from each of the input iterables. The length of the returned iterator is equal to the length of the shortest input iterable.

Here are some examples of using the zip() function:

numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
result = zip(numbers, letters)

for item in result:
    print(item)

Output:

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

In this example, we create two lists numbers and letters, and then call the zip() function with these two lists as arguments. The zip() function returns an iterator that aggregates the elements of the two lists into tuples. We then iterate over the iterator and print each tuple.

Note that the length of the iterator returned by zip() is equal to the length of the shortest input iterable. In this example, both numbers and letters have length 3, so the iterator returned by zip() also has length 3.

The zip() function is useful when you need to iterate over multiple iterables in parallel, for example when you need to iterate over corresponding elements of two lists or when you need to create a dictionary from two lists. It can also be used to unzip a list of tuples into separate lists, using the * operator to unpack the result.