Combine Lists Easily with zip

in #python-dev • 6 days ago

Sometimes we have two lists that belong together.

For example:

names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]

We want to process each name together with the corresponding score.

A beginner might write:

names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]

for i in range(len(names)):
    print(names[i], scores[i])

This works, but Python gives us a cleaner solution: zip().

names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]

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

Output:

Alice 85
Bob 92
Charlie 78

What does zip() do?

zip() combines elements from multiple iterables by position.

You can think of it like this:

["Alice", "Bob", "Charlie"]
   ↓        ↓        ↓
[   85,      92,      78   ]

Python pairs them together as:

("Alice", 85)
("Bob", 92)
("Charlie", 78)

So this:

zip(names, scores)

can be used directly in a loop.

A Practical Example

Imagine we have a list of products and prices:

products = ["Keyboard", "Mouse", "Monitor"]
prices = [49.99, 19.99, 199.99]

for product, price in zip(products, prices):
    print(f"{product}: £{price}")

Output:

Keyboard: £49.99
Mouse: £19.99
Monitor: £199.99

This is much cleaner than manually indexing both lists.

Using zip() with More Than Two Lists

zip() is not limited to two lists.

For example:

names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
grades = ["B", "A", "C"]

for name, score, grade in zip(names, scores, grades):
    print(f"{name}: {score} ({grade})")

Output:

Alice: 85 (B)
Bob: 92 (A)
Charlie: 78 (C)

Important: What if the Lists Have Different Lengths?

Suppose:

names = ["Alice", "Bob", "Charlie"]
scores = [85, 92]

Then:

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

Output:

Alice 85
Bob 92

zip() stops when the shortest iterable is exhausted.

That is important to remember when working with data from different sources.

Converting zip() to a List

You can also inspect the pairs directly:

names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]

pairs = list(zip(names, scores))

print(pairs)

Output:

[('Alice', 85), ('Bob', 92), ('Charlie', 78)]

Creating a Dictionary with zip()

One very useful pattern is combining zip() with dict().

names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]

results = dict(zip(names, scores))

print(results)

Output:

{'Alice': 85, 'Bob': 92, 'Charlie': 78}

This is a simple way to create key-value mappings from two lists.

Small Challenge

Given:

cities = ["London", "Paris", "Tokyo"]
countries = ["UK", "France", "Japan"]

Use zip() to print:

London is in UK
Paris is in France
Tokyo is in Japan

Try solving it before checking the answer.

Solution

cities = ["London", "Paris", "Tokyo"]
countries = ["UK", "France", "Japan"]

for city, country in zip(cities, countries):
    print(f"{city} is in {country}")

Python Tip of the Day

Whenever you find yourself writing:

list1[i]
list2[i]

inside the same loop, check whether zip() can make the code cleaner.

It is especially useful when working with:

  • names and values
  • products and prices
  • timestamps and measurements
  • columns of data
  • API results
  • configuration lists

That's today's Python tip.

Tomorrow we can continue with another small but useful Python feature.

Happy coding! 🐍

#python #programming #coding #tutorial #developer