Skip to content

script_11.py - List Merging with Zip and Chain

Code

See script_11.py for full code.

Explanation

Line 8: from itertools import chain, zip_longest - chain concatenates iterables - zip_longest like zip but handles unequal lengths

Line 11-13: Parallel lists - Three separate lists with related data - Same indices correspond to same person

Line 17: combined = list(zip(names, ages, cities)) - zip() pairs corresponding elements - Returns iterator of tuples - Each tuple has 3 elements (from 3 lists) - Result: [("Alice", 25, "NYC"), ("Bob", 30, "LA"), ...] - Stops at shortest list length

Line 21: users = [{"name": n, "age": a, "city": c} for n, a, c in zip(names, ages, cities)] - List comprehension with tuple unpacking - n, a, c extracts values from each tuple - Creates dict for each person - Converts parallel lists to list of dicts

Line 30: print(f"zip(): {list(zip(list1, list2))}") - Demonstrates zip with unequal lengths - Stops when shorter list exhausted - list2 has only 3 elements, so only 3 pairs created

Line 33: print(f"zip_longest(): {list(zip_longest(list1, list2, fillvalue='N/A'))}") - zip_longest() continues to longest list - fillvalue parameter specifies value for missing elements - Missing elements from shorter list replaced with 'N/A' - Result has 5 tuples (length of longest)

Line 42: all_foods = list(chain(fruits, vegetables, grains)) - chain() takes multiple iterables - Concatenates them sequentially - Returns iterator, converted to list - Alternative to fruits + vegetables + grains - More efficient for many lists

Line 55: records = [dict(zip(headers, row)) for row in [row1, row2, row3]] - Nested structure: list of rows - For each row, zip with headers - dict() converts zipped pairs to dictionary - Creates list of dicts from parallel data