11

This question might be sound subjective, but as "the Zen" says, there is (nearly always) one way to preferred, it shouldn't be subjective at the end.

What way is the better one?

[i.something() for i in l]
map(operator.methodcaller('something'), l)
map(lambda x: x.something(), l)

(1) is (IMO) very clear, but in many answers, map() is used. And if we do so, there is nearly equal readability between (2) and (3) (IMO, at least).

The same counts for many other tasks, but I have chosen this one, as it can stand for all of similiar ones.

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
glglgl
  • 89,107
  • 13
  • 149
  • 217

1 Answers1

9
  • Simple is better than complex.
  • Readability counts.

Both are clear arguments for [i.something() for i in l].

This assumes that .something() doesn't mutate i, and that you're on Python 2.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • 1
    So, if that function mutates, which shall be preferred? – thefourtheye Jan 16 '14 at 07:32
  • 5
    @thefourtheye: None of the above. In that case, an explicit `for` loop would be best: `for item in l: item.something()`. Using list comprehensions or `map`s for side effects is ugly. – Tim Pietzcker Jan 16 '14 at 07:35
  • And the list comprehension is better than the explicit for loop if you want to have a list of the return values. Corollary: methods should either mutate an instance or return something useful, doing both in one method is less good. – RemcoGerlich Jan 16 '14 at 08:37
  • @RemcoGerlich: Right, this is why I made that assumption. But you never know... – Tim Pietzcker Jan 16 '14 at 08:40