[Python][Coding Pattern] Custom Zip

Custom Zip

Purpose

Create a function that mimics Python’s built-in `zip()` — but only for two lists.

It pairs elements at the same index from each list and returns a list of tuples.

If the lists are of different lengths, it stops at the end of the shorter list.

Constraints:

- Do not use Python’s built-in zip().

- The function must support any type of element (integers, strings, booleans, etc.).

- The resulting list must contain tuples like (a[i], b[i]).

Step-by-Step Logic:

1. Define the function with two input lists `a` and `b`.

These lists can contain any type of element.

2. Figure out the stopping condition.

Because the lists might have different lengths, we need to find the shorter length.

We do this using min(len(a), len(b)).

3. Use a list comprehension with indexing.

Loop through the indices from `0` up to (but not including) the shorter length.

For each index `i`, form a tuple:

`(a[i], b[i])` → one item from each list at the same position.

4. Return the full list of tuples.

The list comprehension gathers each tuple and produces the final result.


Key Python Concepts Used:

- range() — to generate indices

- min() — to determine the shorter list length

- List comprehension — compact looping and tuple construction

- Tuple syntax — using `(a[i], b[i])`

# Problem:
# Write a function that behaves like the built-in zip() but only for two lists.
# Requirements:
# Combine two lists element-wise into a list of tuples
# Stop when the shorter list ends
# The function must work with any type of elements
# Do not use the built-in zip()

def custom_zip(a: list, b: list) -> list[tuple]:
    return [(a[i], b[i]) for i in range(min(len(a), len(b)))]


if __name__ == '__main__':
    assert custom_zip([1, 2, 3], ['a', 'b', 'c']) == [(1, 'a'), (2, 'b'), (3, 'c')], 'test 1 failed'
    assert custom_zip([1, 2], ['x', 'y', 'z']) == [(1, 'x'), (2, 'y')], 'test 2 failed'
    assert custom_zip([], ['only']) == [], 'test 3 failed'
    assert custom_zip(['alpha', True], [3.14, None]) == [('alpha', 3.14), (True, None)], 'test 4 failed'

Comments