🐍 Python Beginner

What is Python's zip() function?

Answer

zip(iter1, iter2, ...) takes multiple iterables and pairs up elements at the same position, returning an iterator of tuples. Example: names = ["Alice", "Bob"]; ages = [25, 30]; list(zip(names, ages))[("Alice", 25), ("Bob", 30)]. Zip stops at the shortest iterable. Use itertools.zip_longest() to continue to the longest, filling missing values with a fillvalue. Unzip a list of tuples: names, ages = zip(*pairs). Zip with enumerate: for i, (name, age) in enumerate(zip(names, ages)). Zip with dict comprehension: dict(zip(keys, values)). Zip is excellent for parallel iteration of related sequences, transposing matrices, and combining data from two lists into a structured format.