identity = lambda x: x -- a Pythonic idiom?

George Demmy gdemmy at layton-graphics.com
Sat Nov 17 10:33:56 EST 2001


Hi Hans.

Hans Nowak <wurmy at earthlink.net> writes:
> > 
> > data = filter(identity, crufty_list)
> 
> Note that this can be written as
> 
>   data = filter(None, crufty_list)
> 
> with the same result.

Indeed... thanks for the tip -- just like the library reference
says. Missed that. Interestingly, from the filter entry in library
reference v. 2.0 (underscore emphasis mine):

  filter(function, list)
  Construct a list from those elements of list for which
  function returns true.  If list is a string or a tuple,
  the result also has that type; otherwise it is always a list.
  If function is None, the __identity function__ is assumed,
  i.e. all elements of list that are false (zero or empty) 
  are removed. 

Wouldn't an explicit identity function built-in make this more
"guessable"?  Guessability is one of the things I love about
Python. Actually, an identity function is explicit... no need to
guess.

> > There are, of course, other nifty things to do with identity, and I
> > find it used all the time -- far more often than many Python
> > built-ins. How prevalent is identity usage in the Python community? Is
> > there anyone that would rather suffer hellfire and damnation that do
> > something like this?
> 
> I don't really know what you mean by identity here... lambda x: x, or
> None, in a filter function filters out everything that evaluates as
> "false".

I mean making use of an explicitly defined identity function, or
implicitly defined via lambda x:x, in a variety of contexts, not just
filter. Sorry about the lack of clarity...

Thanks again for pointing out the filter tip. I use filter much I never
would have thought to look it up in the library reference :/ Can't
re-RTFM enough, I 'spose.

G


-- 
George Demmy




More information about the Python-list mailing list