pythonlistmap-function

How can I create my own map() function in Python


I am trying to create the built-in map() function in python. Here is my attempt:

def mapper(func, *sequences):
   if len(sequences) > 1:
       while True:
          list.append(func(sequences[0][0],sequences[0][0],))
       return list
   return list

But I am really stuck, because if the user gives e.g. 100 arguments how do i deal with those?


Solution

  • You use the asterisk * when you call the function:

    def mapper(func, *sequences):
           result = []
           if len(sequences) > 0:
               minl = min(len(subseq) for subseq in sequences)
               for i in range(minl):
                  result.append(func(*[subseq[i] for subseq in sequences]))
           return result

    This produces:

    >>> import operator
    >>> mapper(operator.add, [1,2,4], [3,6,9])
    [4, 8, 13]
    

    By using the asterisk, we unpack the iterable as separate parameters in the function call.

    Note that this is still not fully equivalent, since:

    1. the sequences should be iterables, not per se lists, so we can not always index; and
    2. the result of a map in is an iterable as well, so not a list.

    A more -like map function would be:

    def mapper(func, *sequences):
        if not sequences:
            raise TypeError('Mapper should have at least two parameters')
        iters = [iter(seq) for seq in sequences]
        try:
            while True:
                yield func(*[next(it) for it in iters])
        except StopIteration:
            pass

    Note however that most Python interpreters will implement map closer to the interpreter than Python code, so it is definitely more efficient to use the builtin map, than writing your own.

    N.B.: it is better not to use variable names like list, set, dict, etc. since these will override (here locally) the reference to the list type. As a result a call like list(some_iterable) will no longer work.