0
0
Pythonprogramming~5 mins

zip() function in Python

Choose your learning style9 modes available
Introduction

The zip() function helps you combine multiple lists or sequences into pairs or groups. It makes it easy to work with related items together.

You want to pair names with their ages from two separate lists.
You need to loop over two lists at the same time.
You want to create a list of tuples from multiple lists for easy access.
You want to combine keys and values from two lists into pairs.
You want to process multiple sequences together in a single loop.
Syntax
Python
zip(iterable1, iterable2, ...)

zip() takes two or more sequences (like lists or tuples).

It returns an iterator of tuples, where each tuple contains one item from each sequence.

Examples
Pairs numbers with letters into tuples.
Python
list(zip([1, 2, 3], ['a', 'b', 'c']))
Loops over two lists at the same time, printing pairs.
Python
for x, y in zip([10, 20], [30, 40]):
    print(x, y)
Combines three lists into tuples with three items each.
Python
list(zip([1, 2], ['a', 'b'], [True, False]))
Sample Program

This program pairs each name with an age and prints a sentence for each pair.

Python
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old")
OutputSuccess
Important Notes

If the input lists have different lengths, zip() stops at the shortest list.

You can convert the result of zip() to a list or tuple to see all pairs at once.

Summary

zip() combines multiple sequences into pairs or groups.

It is useful for looping over multiple lists together.

Remember, it stops when the shortest input sequence ends.