Python 101 — zip()
In Python, we have an assortment of built-in functions that allow us to build our programs faster and cleaner. 🧐
One of those functions is zip().
What is zip() Function?
In Python, the zip() function is a built-in function that takes iterables (such as lists, tuples, or strings) and returns an iterator of tuples.
Each tuple contains elements from each of the iterables passed to zip(), corresponding elements are paired together in the resulting tuples.
zip(iterable1, iterable2, ...)
iterable1, iterable2, … are the iterables (lists, tuples, strings, etc.) that you want to zip together.
The zip() function is often used when you need to iterate over multiple iterables simultaneously. For example, when you want to combine data from two lists or perform operations on corresponding elements of multiple lists.
Example 1
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
zipped = zip(list1, list2)
print(list(zipped))
What do you think the output might look like?
Run this replit and check your answer.
Unzipping a Sequence
You can also unzip a sequence using the zip() function along with the * operator.
Example 2
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
numbers, letters = zip(*pairs)
print(numbers)
print(letters)
What do you think the output might look like?
Run this replit and check your answer.
Let’s see some more examples.
Example 3
Suppose you have two lists: one containing the prices of items sold and another containing the quantities of each item sold. You want to calculate the total sales revenue.
# Prices of items sold
prices = [10.99, 5.99, 7.49, 3.99]
# Quantities of each item sold
quantities = [20, 15, 30, 25]
# Calculate total sales using zip() function
total_sales = 0
for price, quantity in zip(prices, quantities):
total_sales += price * quantity
print("Total sales revenue:", total_sales)
What would the total look like?
Run this replit and check your answer.
In this example:
- prices contains the prices of items sold.
- quantities contains the quantities of each item sold.
- We use zip(prices, quantities) to pair each price with its corresponding quantity.
- Inside the loop, for each pair of price and quantity, we calculate the revenue by multiplying the price with the quantity and add it to the total_sales variable.
Example 4
Suppose you have two lists: one containing student names and another containing their corresponding grades for a test. You want to print each student’s name along with their grade.
# Student names
students = ["Alice", "Bob", "Charlie", "David"]
# Grades for the test
grades = [85, 92, 78, 88]
# Print student names and their grades using zip() function
for student, grade in zip(students, grades):
print(f"{student}: {grade}")
What would the output look like?
Run this replit and check your answer.
In this example:
- students contains the names of the students.
- grades contains the corresponding grades for the test.
- We use zip(students, grades) to pair each student with their corresponding grade.
- Inside the loop, for each pair of student and grade, we print the student’s name along with their grade.
Example 5
Let’s see how to unzip a sequence of pairs using the zip() function and the * operator.
# Lists of student names and their corresponding ages
names = ["Alice", "Bob", "Charlie", "David"]
ages = [25, 28, 23, 27]
# Zip lists together to create a sequence of pairs
students_info = zip(names, ages)
# Print original zipped pairs
print("Original zipped pairs:")
for name, age in students_info:
print(f"Name: {name}, Age: {age}")
# Convert iterator to list and unzip again
students_info = list(zip(names, ages))
names, ages = zip(*students_info)
# Print unzipped sequences
print("\nUnzipped again:")
print("Names:", names)
print("Ages:", ages)
What would the output look like?
Run this replit and check your answer.
- We have two lists, names and ages, representing student names and their corresponding ages.
- We initially zip these lists together to create a sequence of pairs, students_info.
- We then iterate over students_info to print out the original zipped pairs.
- After that, we attempt to unzip using zip(*students_info) to separate names and ages again.
Note: By converting students_info to a list before iterating through it again, we ensure that the iterator is not exhausted prematurely.