The zip() function in Python aggregates elements from multiple iterables (lists, tuples, etc.) and returns an iterator of tuples. It’s useful for iterating over multiple sequences simultaneously.
Basic Syntax
zip(*iterables)
Example Usage
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
for num, char in zip(list1, list2):
print(num, char)
# Output:
# 1 a
# 2 b
# 3 c
Converting to a List
zipped = list(zip(list1, list2))
print(zipped) # Output: [(1, 'a'), (2, 'b'), (3, 'c')]
Unzipping
Use the *
operator to unzip:
nums, chars = zip(*zipped)
Conclusion
The zip()
function is a handy tool for working with multiple iterables. It enhances code readability and efficiency.