0

i got a function that takes an object as an argument and calls a method of that object. the method simply prints something out and doesnt return anything.

def func(someobject):
 someobject.method()

now i got a list of a bunch of objects which i want to pass to the "func" function.

I already tried using the map function like this:

list = [object1, object2, object3]
map(func, list)

however it only works when i do:

tuple(map(func, list))

later i want to the method to communicate with an API so my goal is to use multiprocessing to speed up the whole proccess, however i can't even get it right normally xD.

excuse me if I made a rookie mistake, I'm quite new to python and programming in general

4 Answers4

0

map works by itself, my guess is you are confused as it returns an iterator instead of an actual list or tuple. This has been the default behavior starting Python 3 so if you are following an old tutorial, this can seem like a discrepancy in behavior.

FWIW, iterators are, in general, better if your dataset is huge and you don't want to load all items in memory at the same time. You can already use map without the explicit conversion like so:

for spam in map(func, _lst):
  print(spam)
skytreader
  • 11,467
  • 7
  • 43
  • 61
0

map returns an iterator, so it actually has to be evaluated to get the values in it. tuple or list are common ways to do so.

It does this for efficiency purposes: you can map over a massive structure by having it only consume one element from the generator at a time, if you want, e.g.

bar = map(f, foo)

for x in bar:
    baz(x)

You can also feed one generator into another to create more efficient pipelines.

Andy
  • 3,132
  • 4
  • 36
  • 68
0
gen = map(func, liste)

gives you an iterator. You can access the individual elements by

el = next(gen)
Woma
  • 91
  • 3
-1

however it only works when i do

map() works all the time, if you print it will show this:

print(map(func, list))  # <map object at 0x7f6c49ea4880>

The result is a generator so you have to convert it into something like tuple or list.

Ronie Martinez
  • 1,254
  • 1
  • 10
  • 14