Zone Of Makos

Menu icon

Zip in Python

In Python, the zip() function is used to combine two or more iterables into a single iterable. The resulting iterable is a list of tuples, where each tuple contains the elements from the corresponding position in each input iterable. This can be useful for tasks like iterating over multiple lists simultaneously, or for creating dictionaries from two lists.

Using Zip with Lists

When using zip() with lists, the resulting iterable will contain tuples, where each tuple contains the elements from the corresponding position in each list. If the input lists have different lengths, then the resulting iterable will be truncated to the length of the shortest input list.


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

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

Using Zip with Dictionaries

You can also use zip() to create a dictionary from two lists. In this case, the first list contains the keys, and the second list contains the values. If the input lists have different lengths, then the resulting dictionary will be truncated to the length of the shortest input list.


keys = ['a', 'b', 'c']
values = [1, 2, 3]

result = dict(zip(keys, values))
print(result)  # Output: {'a': 1, 'b': 2, 'c': 3}

Using Zip with Different Types of Iterables

The zip() function can also be used with different types of iterables, such as tuples and sets. In this case, the resulting iterable will contain tuples, where each tuple contains the elements from the corresponding position in each input iterable.


tuple1 = (1, 2, 3)
set1 = {'a', 'b', 'c'}

result = zip(tuple1, set1)
print(list(result))  # Output: [(1, 'a'), (2, 'b'), (3, 'c')]

Conclusion

The zip() function in Python allows you to combine two or more iterables into a single iterable. The resulting iterable is a list of tuples, where each tuple contains the elements from the corresponding position in each input iterable. This can be useful for tasks like iterating over multiple lists simultaneously, or for creating dictionaries from two lists. Zip() can be used with different types of iterables, and it is an easy and efficient way to combine data from different sources.