list - Python curiosity: [] > lambda n: n -


one of coworkers using builtin max function (on python 2.7), , found weird behavior.

by mistake, instead of using keyword argument key (as in key=lambda n: n) pre-sort list passed parameter, did:

 >>> max([1,2,3,3], lambda n : n) [1, 2, 3, 3] 

he doing in documentation explained as:

if 2 or more positional arguments provided, largest of positional arguments returned., i'm curious why happens:

>>> (lambda n:n) < [] true >>> def hello(): ...     pass ...  >>> hello < [] true >>> len(hello) traceback (most recent call last):   file "<stdin>", line 1, in <module> typeerror: object of type 'function' has no len() 

i know it's not big deal, i'd appreciate if of stackoverflowers explain how comparisons internally made (or point me direction can find information). :-)

thank in advance!

python 2 orders objects of different types rather arbitrarily. did make lists always sortable, whatever contents. direction comparison comes out not of importance, 1 wins. happens, c implementation falls comparing type names; lambda's type name function, sorts before list.

in python 3, code raise exception instead:

>>> (lambda n: n) < [] traceback (most recent call last):   file "<stdin>", line 1, in <module> typeerror: unorderable types: function() < list() 

because, found out, supporting arbitrary comparisons leads hard-to-crack bugs.


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -