0

Doing some test. I came with a doubt, which option is better, using a map or a for (based on performance, space, time,etc).

map(myfunction,xrange(n))

or

for element in xrange(n):
    myfunction(element)

Thanks.

levi
  • 22,001
  • 7
  • 73
  • 74
  • map is eligant. it's in function language style and it shrinks complicated code to one line. never mention speed to much when you are using python. – Jason Hu Aug 21 '14 at 03:18

2 Answers2

5

As you've written it, definitely go with the for loop. map will create an unnecessary list (of all None since that is presumably the return value of myfunction) on python2.x -- and on python3.x, it won't call your function at all until you actually iterate over the results!

In other words, only use map when you actually want results that you are going to iterate over. Never use it for the side-effects of a function. For forward compatibility, never assume that map's return value is a list -- If you need a list, use a list comprehension:

[myfunction(e) for e in lst]

If you do want an iterable and you are trying to decide between the analogous generator expression and map -- it sort of boils down to a matter of preference. The amount of difference in speed is almost always negligible. I think most prefer the generator expression in terms of aesthetics, but some projects (depending on the developers) may still prefer map. Be consistent with the surrounding code...

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 1
    It can also be useful to write it in terms of `map` if you're expecting to parallelize an expensive function in the future, as many of those toolboxes will offer a parallel `map` analogue that behaves the same. This can make refactoring a little easier. – Roger Fan Aug 21 '14 at 02:39
0

One thing I think about is

for element in list:
    # you can do something to element here
    myfunction(element)

And there is no way to do the same thing in map(myfunction,list)

And also some side effect consideration.

Stephen Lin
  • 4,852
  • 1
  • 13
  • 26