Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map doesn't work as expected in python 3

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.

like image 994
Win Man Avatar asked Feb 04 '14 00:02

Win Man


1 Answers

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.

like image 159
mhlester Avatar answered Sep 29 '22 11:09

mhlester