map doesn't work as expected in python 3

functional-programming, python

Solution

It is generally discouraged to use map to call functions, but that being said, the reason it doesn't work is because Python 3 returns a generator, not a list, so the function isn't called until you've iterated on it. To ensure that it calls the functions:

list(map(extractFunction,files))

But it's creating an unused list. The better approach is to be more explicit:

for file in files:
    extractFunction(file)

As is the case with heads, two lines can indeed be better than one.

Problem

Newbie here. This code worked in python 2.7, but does not in 3.3 ``` def extractFromZipFiles(zipFiles, files, toPath): extractFunction = lambda fileName:zipFiles.extract(fileName, toPath) map (extractFunction,files) return ``` No error but the files are not extracted. However when I replace with for loop works fine. ``` def extractFromZipFiles(zipFiles, files, toPath): for fn in files: zipFiles.extract(fn, toPath) # extractFunction = lambda fileName:zipFiles.extract(fileName, toPath) # map (extractFunction,files) return ``` Code doesn't error.

Original source