Zip Functions

Rina Mondal
2 min readApr 7, 2024

--

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 iterable. It pairs up elements from each iterable, creating tuples of corresponding elements.

Here’s how the zip() function works:

# Syntax
zip(iterable1, iterable2, …)
  1. Zip function on List data type:
# Example
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
zipped = zip(list1, list2) #The result is a zip object, which is an iterator of tuples
print(list(zipped)) #You can convert this zip object into a list of tuples using list(),

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

It’s important to note that if the input iterables passed to zip() are of different lengths, the resulting zip object will have a length equal to the shortest input iterable. Any excess elements from longer iterables will be ignored.

2. Zip function on Tuples Data Type:

# Tuples
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')

# Using zip with tuples
zipped = zip(tuple1, tuple2)

print(list(zipped))
# Output: [(1, 'a'), (2, 'b'), (3, 'c')]

3. Zip function on String Data Type:

# Strings
string1 = "hello"
string2 = "world"

# Using zip with strings
zipped = zip(string1, string2)

print(list(zipped))
# Output: [('h', 'w'), ('e', 'o'), ('l', 'r'), ('l', 'l'), ('o', 'd')]

4. Zip function on different Data Types:

# Different datatypes
list1 = [1, 2, 3]
tuple1 = ('a', 'b', 'c')
string1 = "xyz"

# Using zip with iterables of different datatypes
zipped = zip(list1, tuple1, string1)

print(list(zipped))
# Output: [(1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z')]

Usages of ZIP function:

The zip() function is commonly used in scenarios where you need to iterate over multiple iterables simultaneously, such as when you want to process data from corresponding lists together or when you want to iterate over pairs of elements from two lists in a loop.

--

--

Rina Mondal

I have an 8 years of experience and I always enjoyed writing articles. If you appreciate my hard work, please follow me, then only I can continue my passion.