[Tutor] Re: Are you allowed to shoot camels? [kinda OT]
Roel Schroeven
rschroev_nospam_ml at fastmail.fm
Fri Feb 4 12:38:14 CET 2005
Chad Crabtree wrote:
> How about a concrete example where lambda is more elegant than a
> named
> block of code
>
> aList=['a','bb','ccc','dddd','ee']
> bList=aList[:] #deep copy
> assert not bList is aList
>
> def sortByLength(item1,item2):
> return cmp(len(item1),len(item2))
>
> bList.sort(sortByLength)
> assert bList==['a', 'bb', 'ee', 'ccc', 'dddd']
>
> aList.sort(lambda x,y:cmp(len(x),len(y)))
> assert aList==['a', 'bb', 'ee', 'ccc', 'dddd']
>
> Now this is a concrete example of how lambda simplifies code, at
> least for me because it does not clutter my mental name space. Also
> it is much shorter. However it should be said that this is very much
> a question of taste.
Indeed. In this case, I like the version without lambda. Naming the
function serves as documentation, so I don't even need to read an
interpret the body of the function to know what it does. Assuming that
the name correctly describes the behavior of course, but I need to check
that only once. From then on, sort(sortByLength) instantly explains what
it does, while sort(lambda x,y: cmp(len(x),len(y)) needs much more parsing.
But I agree that there are cases where lambda is more useful and/or clearer.
--
"Codito ergo sum"
Roel Schroeven
More information about the Tutor
mailing list