Sobes.tech
Junior — Middle

Explain how the zip function works in Python and how it combines multiple iterable objects.

sobes.tech AI

Answer from AI

The zip function in Python takes multiple iterable objects (like lists, tuples, strings) and returns an iterator that aggregates elements from each of the iterables into tuples. It pairs the first elements together, then the second, and so on.

zip works until the shortest input iterable is exhausted.

Example:

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

zipped = zip(list1, list2)
print(list(zipped))  # [(1, 'a'), (2, 'b'), (3, 'c')]

If the lists have different lengths:

list1 = [1, 2, 3, 4]
list2 = ['a', 'b']

print(list(zip(list1, list2)))  # [(1, 'a'), (2, 'b')]

Thus, zip is useful for parallel processing of multiple sequences.