zip() Function in Python

Python zip() Function

The zip() function in Python is a built-in function that allows you to combine multiple iterables (such as lists, tuples, or strings) element-wise into a single iterator. It pairs corresponding elements from each iterable together to create tuples. The resulting iterator can be used in various ways, like converting it back to a list or iterating through its elements.

The syntax for the zip() function is as follows:

zip(iterable1, iterable2, ...)

Parameters:

  • iterable1, iterable2, ...: Two or more iterables (lists, tuples, strings, etc.) that you want to combine element-wise.

Returns:

  • An iterator of tuples, where each tuple contains elements from the corresponding positions of the input iterables.

Here's an example of how to use the zip() function:

# Example 1: Combining lists
names = ["Alice", "Bob", "Charlie"]
ages = [30, 25, 35]

# Using zip() to combine lists element-wise
combined_data = zip(names, ages)

# Converting the iterator to a list (optional)
result_list = list(combined_data)
print(result_list)
# Output: [('Alice', 30), ('Bob', 25), ('Charlie', 35)]

# Example 2: Combining different types of iterables
numbers = [1, 2, 3]
letters = "ABC"

# Using zip() with a list and a string
combined_data = zip(numbers, letters)

# Converting the iterator to a list (optional)
result_list = list(combined_data)
print(result_list)
# Output: [(1, 'A'), (2, 'B'), (3, 'C')]

# Example 3: Zip with different-length iterables
names = ["Alice", "Bob", "Charlie"]
ages = [30, 25]

# Using zip() with different-length iterables
combined_data = zip(names, ages)

# Converting the iterator to a list (optional)
result_list = list(combined_data)
print(result_list)
# Output: [('Alice', 30), ('Bob', 25)]

Note that when using zip(), it will stop combining elements as soon as the shortest input iterable is exhausted. If you want to work with all elements, even if the iterables are of different lengths, you can use itertools.zip_longest() from the itertools module.