What is the purpose of the zip() function in Python?

Long Answer
Views 147

Answer:

The zip function in Python is used to combine two or more iterables into a single iterable of tuples. Each tuple contains the n-th elements from each of the iterables. The function is particularly useful when you need to process multiple lists in parallel, for example, when iterating over multiple lists at the same time.

Here's an example of how you can use the zip function to combine two lists:


# Two lists
list1 = [1, 2, 3, 4]
list2 = ['a', 'b', 'c', 'd']

# Combine the lists using the zip function
result = list(zip(list1, list2))

print(result)

Output:


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

As you can see, the zip function has combined the elements from the two lists into a single list of tuples, where each tuple contains the corresponding elements from each list.

If the iterables have different lengths, the zip function will stop as soon as it runs out of elements in the shortest iterable:


# Two lists of different lengths
list1 = [1, 2, 3, 4]
list2 = ['a', 'b', 'c']

# Combine the lists using the zip function
result = list(zip(list1, list2))

print(result)

Output:


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

The zip function can also be used with more than two iterables. In this case, each tuple will contain the n-th elements from each of the iterables:


# Three lists
list1 = [1, 2, 3, 4]
list2 = ['a', 'b', 'c', 'd']
list3 = [10, 20, 30, 40]

# Combine the lists using the zip function
result = list(zip(list1, list2, list3))

print(result)

Output:


[(1, 'a', 10), (2, 'b', 20), (3, 'c', 30), (4, 'd', 40)]

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Python, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.