zip(): Pairing Lists Together

Published:
Last updated:
By Jeferson Peter
Python

Combining lists

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

paired = list(zip(names, scores))
print(paired)

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

Iterating pairs

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

# Alice scored 85
# Bob scored 92
# Charlie scored 78

Unzip with *

zipped = list(zip(names, scores))
unzipped_names, unzipped_scores = zip(*zipped)
print(unzipped_names)
print(unzipped_scores)

# ('Alice', 'Bob', 'Charlie')
# (85, 92, 78)

Conclusion

zip() makes pairing clean and Pythonic. With the * operator, you can also easily reverse the process.