user2076561
user2076561

Reputation: 159

Python(3.3) map function behaviour

import glob,os

os.chdir("C:\\path")

after this if I execute a line

map(lambda y:os.remove(y),filter(lambda x:os.path.getsize(x)==0,glob.glob('*')))

it does not remove the files of size zero

But if I do this

list(map(lambda y:os.remove(y),filter(lambda x:os.path.getsize(x)==0,glob.glob('*'))))

it removes the files. How does this actually work?

Upvotes: 0

Views: 67

Answers (2)

falsetru
falsetru

Reputation: 369134

map in Python 3.x returns an iterator. The function passed to the map is not called until the iterator is iterated.

list consumes the iterator; causing the function to be called.

Upvotes: 0

starrify
starrify

Reputation: 14751

In Python3 the map function returns a map object (instead of a list in Python2).
This is designed for lazy evaluation, which means the value was not evaluated before used. And list evaluates it.

Upvotes: 1

Related Questions