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

Erik Max Francis max at alcyone.com
Sat Nov 17 15:01:06 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)

This doesn't even make sense to me.  filter applies the function for
each element in the sequence, and returns a new list of only those
elements for which the function returned true.  Why is using the
identity function for this purpose useful?

If you really want to select the true sequence, then from a mathematical
standpoint what you want is operator.truth, not the identity function. 
Obviously they do the same thing in this context, but they have
different meanings.  (Or a None passed as the function would as well.)

> 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?

There's nothing wrong with using an identity function in context (though
your claim that you use it more often than many builtins is strange,
since it explicitly doesn't do anything).  I'm just curious what you're
doing such that the identity function pops up very frequently.  It could
be there's a better way to get what you're going after.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ Laws are silent in time of war.
\__/ Cicero
    Esperanto reference / http://www.alcyone.com/max/lang/esperanto/
 An Esperanto reference for English speakers.



More information about the Python-list mailing list