[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])`
Comments
Post a Comment