Notes

`zip()` Function in Python [ English ]

< Prev Next >

1. Introduction

The zip() function in Python is a built-in function used to combine multiple iterable objects (such as lists, tuples, or strings) into a single iterator of tuples. Each tuple contains elements from the corresponding position of the given iterables.

In simple terms, zip() pairs elements from different sequences together based on their index position.

The function is very useful when we want to iterate over multiple sequences simultaneously.

2. Syntax

zip(iterable1, iterable2, ..., iterableN)

Parameters

Return Value

3. Basic Example

numbers = [1, 2, 3]
letters = ['a', 'b', 'c']

result = zip(numbers, letters)

print(list(result))

Output

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

Explanation

4. Using zip() in a Loop

names = ["Rahul", "Amit", "Priya"]
marks = [85, 90, 88]

for name, mark in zip(names, marks):
    print(name, mark)

Output

Rahul 85
Amit 90
Priya 88

Explanation

5. Example with Different Length Iterables

a = [1, 2, 3, 4]
b = ['x', 'y']

print(list(zip(a, b)))

Output

[(1, 'x'), (2, 'y')]

Explanation

6. Using zip() with Three Iterables

names = ["Rahul", "Amit", "Priya"]
marks = [85, 90, 88]
grades = ["A", "A+", "A"]

print(list(zip(names, marks, grades)))

Output

[('Rahul', 85, 'A'), ('Amit', 90, 'A+'), ('Priya', 88, 'A')]

Explanation

7. Unzipping Using zip()

zip() can also be used to separate paired elements back into individual sequences.

pairs = [(1, 'a'), (2, 'b'), (3, 'c')]

numbers, letters = zip(*pairs)

print(numbers)
print(letters)

Output

(1, 2, 3)
('a', 'b', 'c')

Explanation

8. Practical Example

subjects = ["Math", "Physics", "Chemistry"]
marks = [80, 75, 90]

student_record = dict(zip(subjects, marks))

print(student_record)

Output

{'Math': 80, 'Physics': 75, 'Chemistry': 90}

Explanation

9. Advantages of zip()

10. Summary

< Prev Next >