Win Man
Win Man

Reputation: 929

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.

Upvotes: 8

Views: 3249

Answers (2)

mhlester
mhlester

Reputation: 23231

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.

Upvotes: 13

inspectorG4dget
inspectorG4dget

Reputation: 113975

map in python3 is an iterator, whereas in python2, it computed a list. So, what you're looking for, is a way to consume the entire iterator. Thankfully, there's an itertools recipe for this:

import collections
def extractFromZipFiles(zipFiles, files, toPath):
    extractFunction = lambda fileName:zipFiles.extract(fileName, toPath) 
    collections.deque(map(extractFunction,files), maxlen=0)
    return

Upvotes: 0

Related Questions