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

Hans Nowak wurmy at earthlink.net
Sat Nov 17 10:05:38 EST 2001


George Demmy wrote:
> 
> I do a bunch of list-oriented programming with a bunch of one-off
> programs. For a variety of reasons these lists tend to have a bit
> of cruft associated with them (I don't write it -- just process
> it!). So stuff like this shows up quite a bit:
> 
> data = filter(lambda x: x, crufty_list)
> 
> I did it so often, that stuff like this shows up:
> 
> identity = lambda x: x # like this in practice (lazy)
> 
> def identity(x): # Pythonic -- shows up in profiler, etc
>     return x
> 
> data = filter(identity, crufty_list)

Note that this can be written as

  data = filter(None, crufty_list)

with the same result.

> 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".



More information about the Python-list mailing list