Sunday, January 11, 2009

Another way to think about lambda

Until now I had problems understanding the lambda statement. I did not know how is it used and what does it actually do. The description in the Python documentation did explain it but not easy enought to remember it.

Now I have thought of something which helps me remember the purpose of lambda and its syntax.

It's the same like functions in the math class:

f(x) = x+1

is the same as:

lambda x: x + 1

Sorting by class attributes

When you need to sort a sequence (e. g. a list) of objects you probably want to sort them by one of their attributes. How to to that?

Let's have this simple class:


class Record:
    def __init__(self):
        self.name = "noname"


now we have three objects of this class:


>>> r = Record()
>>> s = Record()
>>> t = Record()


And we give them some names


>>> r.name = "qwer"
>>> s.name = "asdf"
>>> t.name = "yxcv"


We have them in a list

>>> someList = [r, s, t]

And we want them to be sorted by their attribute name. This can be done by specifying the key argument of the sequence method .sort():


>>> someList.sort(key = lambda x: x.name)


That's all. The objects in the list are sorted by their name attributes.

P.S.:
The lambda x: x.name is a minimal function. For every x it returns x.name