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)]
Unzip back:
names_back, scores_back = zip(*paired)
print(list(names_back)) # ['Alice', 'Bob', 'Charlie']
Enumerate for index and value
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Start from different number:
for index, fruit in enumerate(fruits, start=1):
print(index, fruit) # 1 apple, 2 banana, 3 cherry
Simple examples
Student report:
students = ["Ali", "Sara", "Reza"]
grades = [18, 20, 17]
for student, grade in zip(students, grades):
print(f"{student}: {grade}")
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}")
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)