identity = lambda x: x -- a Pythonic idiom?
Marco Antoniotti
marcoxa at cs.nyu.edu
Sun Nov 18 13:18:08 EST 2001
George Demmy <gdemmy at layton-graphics.com> writes:
> 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)
>
> 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?
>
> Curiously,
The function `identity' is part of the Common Lisp standard. It is
defined extacly as you suspected.
Within CL, it turns out that `identity' is useful in a number of
cases, especially when dealing with sequence operators. E.g. the
`sort' function is really defined as
sort <sequence> <predicate> &key (key #'identity)
So that you can write things like
* (sort '(2 3 4 1) #'<)
'(1 2 3 4)
* (sort '((1 3) (3 0) (33 9) (19 5)) #'< :key #'second)
((3 0) (1 3) (19 5) (33 9))
All in all a good thing.
Cheers
--
Marco Antoniotti ========================================================
NYU Courant Bioinformatics Group tel. +1 - 212 - 998 3488
719 Broadway 12th Floor fax +1 - 212 - 995 4122
New York, NY 10003, USA http://bioinformatics.cat.nyu.edu
"Hello New York! We'll do what we can!"
Bill Murray in `Ghostbusters'.
More information about the Python-list
mailing list