Why this behavior? (was: Stupid Lambda Tricks)
Daniel Berlin
dan at dberlin.org
Thu Feb 21 09:01:23 EST 2002
On Thursday, February 21, 2002, at 07:20 AM, Jonathan Gardner wrote:
> < snip excellent lambda tricks >
>>
>> Many list functions return None, so you cannot easily use them in a
>> stacked expression inside lambda. Examples of this are [].sort() and
>> [].reverse(). Instead of writing:
>>
>> list.some_function_that_returns_None()
>> function(list)
>>
>> you can write
>>
>> function((list.some_function_that_returns_None(),list)[1])
>>
>> Here is an example:
>>
>> import random
>>
>> sort = lambda x: (x.sort(),x)[1]
>> reverse = lambda x: (x.reverse(),x)[1]
>>
>
> I've always wondered:
>
>>>> "abc".upper()
> "ABC"
>>>> [3,1,2].sort()
> < nothing >
>
> Why is that? Is it just easier to implement it this way, or is there
> some
> sound philosophical reason for this?
Sound reason, IIRC (someone will correct me if i'm wrong).
Upper returns a *new* string with the letters upper-cased. The original
is not affected.
On the other hand, sort/reverse are *in-place*, and affect the original.
Returning the "new" original would give the impression that the original
had not been affected.
--Dan
More information about the Python-list
mailing list