CodingNic

Loops and Iteration

Zip

Loops and Iteration 18 min read

Zip

Zip

Sometimes you have two groups of data that belong together.

For example:

  • Names and scores
  • Products and prices
  • Countries and capitals

You may want to loop through both groups at the same time.

Python gives us a helpful tool called zip().

What Is Zip?

zip() joins items from two or more groups.

Then you can loop through them together.

python
names = ["Ali", "Sara", "John"]
scores = [80, 90, 75]

for name, score in zip(names, scores):
    print(name, score)

Output

text
Ali 80
Sara 90
John 75

How This Works

Let’s break it down:

  • First name goes with first score
  • Second name goes with second score
  • Third name goes with third score

Python matches items by position.

Another Example

python
products = ["Book", "Pen", "Bag"]
prices = [10, 2, 25]

for product, price in zip(products, prices):
    print(product, price)

Output

text
Book 10
Pen 2
Bag 25

If One Group Is Shorter

zip() stops when the shortest group ends.

python
names = ["Ali", "Sara"]
scores = [80, 90, 75]

for name, score in zip(names, scores):
    print(name, score)

Output

text
Ali 80
Sara 90

Only two pairs are created because the names list ends first.

Using Three Groups

You can also join more than two groups.

python
names = ["Ali", "Sara"]
scores = [80, 90]
grades = ["B", "A"]

for name, score, grade in zip(names, scores, grades):
    print(name, score, grade)

Output

text
Ali 80 B
Sara 90 A

Why Zip Is Useful

zip() keeps related data together while looping.

It makes code cleaner and easier to understand.

Code Along

python
days = ["Mon", "Tue", "Wed"]
tasks = ["Code", "Study", "Rest"]

for day, task in zip(days, tasks):
    print(day, task)

Output

text
Mon Code
Tue Study
Wed Rest

Mini Challenge

Build a price list.

Steps:

  • Create a list of products:
    Book, Pen, Bag
  • Create a list of prices:
    10, 2, 25
  • Use zip()
  • Print each product with its price

Expected output:

text
Book 10
Pen 2
Bag 25

Real World Use Case

Apps use zip() to combine names with scores, products with prices, and labels with values in reports.

Quiz

  1. What does zip() do?
  2. How does Python match items?
  3. What happens if one group is shorter?
  4. Can zip() join three groups?

Assignment

Create a program that combines countries with capitals and prints them using zip().

Summary

You learned how zip() joins related data and helps you loop through multiple groups at the same time.