Reputation: 1917
So I am trying to figure out how Python's map()
function works as a way to speed up my program a little bit. From my basic understanding it looks like you can use map()
to replace certain instances where you'd use a for
loop. What I'm curious about is can you change something like:
loopNum = 25
for i in range (loopNum):
self.doSomething()
To:
loopNum = 25
map(self.doSomething(), range(loopNum))
Additionally, in the above example, would I be able to forego that loopNum
variable, and in the map just have map(something, 25)
?
Upvotes: 0
Views: 86
Reputation: 4643
map
is roughly the equivalent of this for
loop:
# my_map(func, iter1, iterN...)
def my_map(func, *iteables)
for x, y,... in zip(iter1, iter2,iterN...):
yield func(x,y,...)
What you're doing in your code is just like this:
my_map(self.doSomething(), range(loopNum))
self.dSomething()
must return a function or a callable object or this obviously doesn't work. This is because, whatever object you pass into the func
argument of my_map
function will be called then in addition to passing the right number of arguments to func
, func
must be a callable object as well :-)
*You must iterate over the iterable returned by map
to obtain the results, otherwise, you would just get an iterable object without tangible work.
Upvotes: 1
Reputation: 6891
I want to add to this question that map()
is virtually never the right tool in Python. Our BDFL himself, wanted to remove it from Python 3, together with lambda
s and, most forcefully reduce
.
In almost all cases where you feel tempted to use map()
take a step back and try to rewrite your code using list comprehension instead. For your current example, that would be:
my_list = [self.doSomething() for i in range(loopNum)]
or
my_generator = (self.doSomething() for i in range(loopNum))
to make it a generator instead.
But for this to make any sense at all, self.doSomething()
should probably take the variable i
as an input. After all you are trying to map the values in your range to something else.
Upvotes: 0
Reputation: 44886
No, you can't as map(function, iterable)
applies function
to each element of the iterable. If you simply want to execute some functionn
times, just use a loop.
Note that iterable
must be (surprise!) an iterable, not a number.
Upvotes: 4