Search code examples
pythonpython-3.xfunctional-programmingmap-function

Trouble using map() in python to update an existing list


Why is this returning an empty list:

def word_lengths(phrase):

    result = []
    map(lambda x: result.append(x) , phrase.split())
    return result

Where as this returns a list of the length of each word in the phrase:

def word_lengths(phrase):

    return list(map(lambda x: len(x) , phrase.split()))

Solution

  • In Python 3, map results in a generator, which is lazily evaluated.

    You need to iterate over it to take effect, for example by calling the list constructor on it:

    result = []
    list(map(lambda x: result.append(x) , phrase.split()))
    return result
    

    This mutates result as you had probably expected.

    Note though, that the same can be achieved in a much simpler way:

    return phrase.split()