Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

Custom zip

The built-in zip function “zips” two lists. Write your own implementation of this function.

Define a function named zap. The function takes two parameters, a and b. These are lists.

Your function should return a list of tuples. Each tuple should contain one item from the a list and one from b.

You may assume a and b have equal lengths.

If you don’t get it, think of a zipper.

For example:

zap(
    [0, 1, 2, 3],
    [5, 6, 7, 8]
)

Should return:

[(0, 5),
 (1, 6),
 (2, 7),
 (3, 8)]


==== SOLUTION ====

You can implement the `zap` function in Python by iterating over both lists simultaneously using a loop and constructing tuples containing elements from each list. Here’s how you can do it:

“`python
def zap(a, b):
       result = []
      for i in range(len(a)):
            result.append((a[i], b[i]))
      return result

 

# Test the function
print(zap([0, 1, 2, 3], [5, 6, 7, 8]))
“`

This will output:

“`
[(0, 5),
(1, 6),
(2, 7),
(3, 8)]
“`

Explanation:

1. `def zap(a, b):`: This line defines a function named `zap` that takes two parameters `a` and `b`, which are lists.

2. `result = []`: This line initializes an empty list `result` to store the tuples containing elements from both lists.

3. `for i in range(len(a)):`: This loop iterates over the indices of the lists. Since `a` and `b` have equal lengths, `len(a)` is used to determine the number of iterations.

4. `result.append((a[i], b[i]))`: Within the loop, this line constructs a tuple containing the elements at the current index `i` from lists `a` and `b`, and appends this tuple to the `result` list.

5. Finally, the function returns the `result` list containing tuples of elements from both lists.

This function mimics the behavior of the built-in `zip()` function by zipping together elements from two lists into tuples.



Join the conversation