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.
The Zen of Python is a collection of 19 "guiding principles" for writing computer programs that influence the design of the Python programming language. Software engineer Tim Peters wrote this set of principles and posted it on the Python mailing list in 1999.
Came to be known as “The Zen of Python”, these aphorisms exploded amongst Python developers. Tim Peters wrote these BDFL's (Benevolent Dictator For Life, a nickname of Python creator Guido van Rossum) 20 guiding principles for Python's design but the last aphorism was left for van Rossum to fill in.
Thanks to his contribution, anyone can view the Zen straight from the Python interpreter by typing import this : >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit.
As soon as we'd chosen "import this" I realized we just had to implement it. Python 2.2 was about to be released and I proposed that we turn off check-in notifications and sneak in a "this.py" module which when imported just printed the Zen of Python.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With