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

George Demmy gdemmy at layton-graphics.com
Sat Nov 17 12:43:03 EST 2001


"Andrew Dalke" <dalke at dalkescientific.com> writes:
> George Demmy:
> >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)
> 
> Isn't this the same as operator.truth?

operator.truth and the identity function are not exactly the same.
operator.truth returns 1 if true, 0 if false. identity returns its
argument, so:

map(operator.truth, (0, 1, "Hi Andrew!")) -> [0, 1, 1]
map(lambda x: x, (0, 1, "Hi Andrew!")) -> [0, 1, "Hi Andrew!"]

With map, of course, one can imply identity with None, e.g.,

map(None, (0, 1, "Hi Andrew!")) -> [0, 1, "Hi Andrew!"]

For filtering purposes, they have the same effect.


G


--
George Demmy



More information about the Python-list mailing list