Table of Contents

    zip()

    CHAPTER 29.4 · ADVANCED PYTHON FEATURES

    zip() in Python

    Learn how to combine corresponding values from two or more Python iterables using the built-in zip() function.

    Python applications often store related data in separate collections. For example, one list may contain employee names, while another contains their departments.

    The built-in zip() function combines corresponding values from multiple iterables. It produces tuples containing one value from each supplied iterable.

    Learning objective: In this tutorial, you will learn how to combine collections, unpack generated tuples, handle different input lengths, create dictionaries, and separate zipped values.

    Prerequisites

    What You Should Know

    • Python lists and tuples
    • Using for loops
    • Tuple unpacking
    • Basic knowledge of dictionaries
    • Using list comprehension
    • Basic understanding of iterables

    What is zip()?

    zip() is a built-in Python function that accepts multiple iterables and returns a zip object.

    During iteration, the zip object produces tuples containing corresponding values from the supplied iterables.

    Think of zip() as joining table columns

    Each iterable behaves like a column. The first values form the first row, the second values form the second row, and the process continues for the remaining values.

    Syntax

    ZIP SYNTAX
    zip(iterable1, iterable2, ...)
    zip(iterable1, iterable2)

    Basic Example

    names = [
        "Amina",
        "Rahul",
        "David"
    ]
    
    departments = [
        "IT",
        "Finance",
        "Sales"
    ]
    
    for name, department in zip(
        names,
        departments
    ):
        print(name, department)

    Output:

    Amina IT
    Rahul Finance
    David Sales

    Each generated tuple contains a name and the department found at the corresponding position.

    What Does zip() Return?

    names = ["Amina", "Rahul"]
    scores = [85, 91]
    
    result = zip(
        names,
        scores
    )
    
    print(type(result))

    Output:

    <class 'zip'>
    zip() returns a zip object. Iterate over it or convert it to a collection to inspect its values.

    Convert zip() to a List

    names = [
        "Amina",
        "Rahul",
        "David"
    ]
    
    scores = [
        85,
        91,
        78
    ]
    
    records = list(
        zip(
            names,
            scores
        )
    )
    
    print(records)

    Output:

    [('Amina', 85), ('Rahul', 91), ('David', 78)]

    Combine Three Iterables

    names = [
        "Amina",
        "Rahul",
        "David"
    ]
    
    departments = [
        "IT",
        "Finance",
        "Sales"
    ]
    
    salaries = [
        65000,
        58000,
        62000
    ]
    
    for name, department, salary in zip(
        names,
        departments,
        salaries
    ):
        print(
            name,
            department,
            salary
        )

    Output:

    Amina IT 65000
    Rahul Finance 58000
    David Sales 62000

    Iterables with Different Lengths

    By default, zip() stops when the shortest iterable has no remaining values.

    names = [
        "Amina",
        "Rahul",
        "David"
    ]
    
    departments = [
        "IT",
        "Finance"
    ]
    
    records = list(
        zip(
            names,
            departments
        )
    )
    
    print(records)

    Output:

    [('Amina', 'IT'), ('Rahul', 'Finance')]
    Important David is not included because the departments list does not contain a corresponding third value.

    Detect Different Lengths

    Use strict=True when all supplied iterables must have the same length.

    names = [
        "Amina",
        "Rahul",
        "David"
    ]
    
    departments = [
        "IT",
        "Finance"
    ]
    
    try:
        records = list(
            zip(
                names,
                departments,
                strict=True
            )
        )
    
        print(records)
    
    except ValueError:
        print(
            "The input collections have different lengths."
        )
    Strict checking is useful when missing corresponding values indicate incomplete or invalid data.

    Create a Dictionary

    Use one iterable as dictionary keys and another as dictionary values.

    employee_ids = [
        "EMP-101",
        "EMP-102",
        "EMP-103"
    ]
    
    employee_names = [
        "Amina",
        "Rahul",
        "David"
    ]
    
    employees = dict(
        zip(
            employee_ids,
            employee_names
        )
    )
    
    print(employees)

    Output:

    {'EMP-101': 'Amina', 'EMP-102': 'Rahul', 'EMP-103': 'David'}

    Perform Parallel Calculations

    Calculate the total amount for every product:

    quantities = [
        2,
        5,
        3
    ]
    
    unit_prices = [
        100,
        250,
        400
    ]
    
    line_totals = [
        quantity * unit_price
        for quantity, unit_price in zip(
            quantities,
            unit_prices
        )
    ]
    
    print(line_totals)

    Output:

    [200, 1250, 1200]

    Calculate the complete invoice amount:

    total_amount = sum(
        quantity * unit_price
        for quantity, unit_price in zip(
            quantities,
            unit_prices
        )
    )
    
    print(total_amount)

    Output:

    2650

    Combine zip() with enumerate()

    names = [
        "Amina",
        "Rahul",
        "David"
    ]
    
    departments = [
        "IT",
        "Finance",
        "Sales"
    ]
    
    for number, employee_data in enumerate(
        zip(
            names,
            departments
        ),
        start=1
    ):
        name, department = employee_data
    
        print(
            number,
            name,
            department
        )

    Output:

    1 Amina IT
    2 Rahul Finance
    3 David Sales

    Nested unpacking can make the loop shorter:

    for number, (name, department) in enumerate(
        zip(
            names,
            departments
        ),
        start=1
    ):
        print(
            number,
            name,
            department
        )

    Unzip Combined Values

    Use the unpacking operator to separate combined records:

    employee_records = [
        ("Amina", "IT"),
        ("Rahul", "Finance"),
        ("David", "Sales")
    ]
    
    names, departments = zip(
        *employee_records
    )
    
    print(names)
    print(departments)

    Output:

    ('Amina', 'Rahul', 'David')
    ('IT', 'Finance', 'Sales')

    Transpose a Matrix

    Transposing a matrix changes its rows into columns.

    matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]
    
    transposed_matrix = [
        list(column)
        for column in zip(
            *matrix
        )
    ]
    
    print(transposed_matrix)

    Output:

    [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

    zip Object Exhaustion

    A zip object is consumed when its values are requested.

    names = ["Amina", "Rahul"]
    scores = [85, 91]
    
    records = zip(
        names,
        scores
    )
    
    print(list(records))
    print(list(records))

    Output:

    [('Amina', 85), ('Rahul', 91)]
    []
    Important A consumed zip object cannot restart. Call zip() again when another iteration is required.

    Practical Example: Invoice Records

    products = [
        "Laptop",
        "Keyboard",
        "Mouse"
    ]
    
    quantities = [
        1,
        2,
        3
    ]
    
    unit_prices = [
        75000,
        2500,
        1200
    ]
    
    for product, quantity, unit_price in zip(
        products,
        quantities,
        unit_prices,
        strict=True
    ):
        line_total = quantity * unit_price
    
        print(
            product,
            quantity,
            unit_price,
            line_total
        )

    Output:

    Laptop 1 75000 75000
    Keyboard 2 2500 5000
    Mouse 3 1200 3600

    Common Mistakes

    1

    Expecting a List

    zip() returns a zip object, not a list.

    Solution Iterate over it or convert it using list().
    2

    Ignoring Unequal Lengths

    Standard zip() stops at the shortest iterable.

    Solution Validate input lengths or use strict=True when equal lengths are required.
    3

    Incorrect Tuple Unpacking

    The number of variables must match the number of supplied iterables.

    Solution Use one unpacking variable for every supplied iterable.
    4

    Reusing a Consumed zip Object

    A zip object becomes exhausted after iteration.

    Solution Create a new zip object or store the results in a list when repeated access is required.
    5

    Confusing zip() with ZIP Files

    The zip() function combines iterable values. It does not create compressed archive files.

    Best Practices

    Recommended Practices

    • Use descriptive variable names while unpacking tuples.
    • Keep corresponding values in the same logical order.
    • Validate lengths when unmatched values indicate bad data.
    • Use strict checking when every record must have a match.
    • Convert to a list only when all pairs must be stored or reused.
    • Use enumerate() for simple numbering of one iterable.
    • Create a new zip object when another pass is required.

    Hands-On Practice

    Practice Exercises

    • Combine student names with their marks.
    • Combine product names, quantities, and unit prices.
    • Add corresponding numbers from two lists.
    • Create a dictionary from separate key and value lists.
    • Detect unequal input lengths.
    • Unzip employee records into separate collections.
    • Combine zip() with enumerate().
    • Transpose a matrix using zip().

    Knowledge Check

    1

    What does zip() return?

    It returns a zip object that produces tuples containing corresponding values from the supplied iterables.

    2

    What happens when lengths differ?

    Standard zip() stops when the shortest iterable is exhausted.

    3

    How do you create a dictionary?

    result = dict(
        zip(
            keys,
            values
        )
    )
    4

    How do you unzip records?

    first_values, second_values = zip(
        *records
    )

    zip() Quick Reference

    # Combine two iterables
    records = zip(
        first_values,
        second_values
    )
    
    # Iterate with unpacking
    for first, second in zip(
        first_values,
        second_values
    ):
        print(first, second)
    
    # Convert to a list
    records = list(
        zip(
            first_values,
            second_values
        )
    )
    
    # Combine three iterables
    records = zip(
        first_values,
        second_values,
        third_values
    )
    
    # Require equal lengths
    records = zip(
        first_values,
        second_values,
        strict=True
    )
    
    # Create a dictionary
    mapping = dict(
        zip(
            keys,
            values
        )
    )
    
    # Unzip records
    first_values, second_values = zip(
        *records
    )

    Summary

    What You Learned

    • zip() combines corresponding values from multiple iterables.
    • It returns a zip object that produces tuples.
    • Generated tuples can be unpacked directly in a loop.
    • Standard zip() stops at the shortest input.
    • Strict checking can detect unequal input lengths.
    • Zipped values can be converted into lists or dictionaries.
    • The unpacking operator can separate zipped records.
    • A zip object becomes exhausted after its values are consumed.

    Key Takeaway

    Use zip() when corresponding values from multiple iterables must be processed together. Validate input lengths when missing matches matter and remember that the returned zip object is consumed during iteration.