DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Working with Multiple Lists in Python Explained Simply (Zip and More)

You can work with several lists together using built-in functions.

Using zip to combine lists

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

paired = list(zip(names, scores))
print(paired)  # [('Alice', 85), ('Bob', 92), ('Charlie', 78)]
Enter fullscreen mode Exit fullscreen mode

Unzip back:

names_back, scores_back = zip(*paired)
print(list(names_back))  # ['Alice', 'Bob', 'Charlie']
Enter fullscreen mode Exit fullscreen mode

Enumerate for index and value

fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):
    print(index, fruit)
Enter fullscreen mode Exit fullscreen mode

Start from different number:

for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)  # 1 apple, 2 banana, 3 cherry
Enter fullscreen mode Exit fullscreen mode

Simple examples

Student report:

students = ["Ali", "Sara", "Reza"]
grades = [18, 20, 17]

for student, grade in zip(students, grades):
    print(f"{student}: {grade}")
Enter fullscreen mode Exit fullscreen mode

Rank items:

items = ["book", "pen", "notebook"]
prices = [10, 2, 15]

for rank, (item, price) in enumerate(sorted(zip(prices, items)), start=1):
    print(f"Rank {rank}: {item} - ${price}")
Enter fullscreen mode Exit fullscreen mode

Quick summary

  • Combine with zip().
  • Get index with enumerate().
  • Unzip with *.
  • Useful for parallel processing of lists.

Practice combining lists. These tools help handle multiple collections together in Python programs.

Top comments (0)