Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a map without result in python?

Sometimes, I just want to execute a function for a list of entries -- eg.:

for x in wowList:    installWow(x, 'installed by me') 

Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:

map(lambda x: installWow(x, 'installed by me'), wowList) 

But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.

(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)

like image 996
Juergen Avatar asked Jul 03 '09 16:07

Juergen


People also ask

Is map better than for loop Python?

map() works way faster than for loop. Considering the same code above when run in this ide.

What is * map in Python?

Map in Python is a function that works as an iterator to return a result after applying a function to every item of an iterable (tuple, lists, etc.). It is used when you want to apply a single transformation function to all the iterable elements. The iterable and function are passed as arguments to the map in Python.

Is there a map object in Python?

Python map() function is used to apply a function on all the elements of specified iterable and return map object. Python map object is an iterator, so we can iterate over its elements. We can also convert map object to sequence objects such as list, tuple etc. using their factory functions.

What does map () do in Python?

Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.


2 Answers

You could make your own "each" function:

  def each(fn, items):     for item in items:         fn(item)   # called thus each(lambda x: installWow(x, 'installed by me'), wowList)  

Basically it's just map, but without the results being returned. By using a function you'll ensure that the "item" variable doesn't leak into the current scope.

like image 139
John Montgomery Avatar answered Sep 22 '22 06:09

John Montgomery


How about this?

for x in wowList:     installWow(x, 'installed by me') del x 
like image 29
RichieHindle Avatar answered Sep 23 '22 06:09

RichieHindle