lambda vs. operator.attrgetter('xxx') as sort key function in Python

Posted by Paul McGuire on Stack Overflow See other posts from Stack Overflow or by Paul McGuire
Published on 2010-04-24T15:56:37Z Indexed on 2010/04/24 16:53 UTC
Read the original article Hit count: 147

Filed under:
|
|

I am looking at some code that has a lot of sort calls using comparison functions, and it seems like it should be using key functions.

If you were to change seq.sort(lambda x,y: cmp(x.xxx, y.xxx)), which is preferable:

seq.sort(key=operator.attrgetter('xxx'))

or:

seq.sort(key=lambda a:a.xxx)

I would also be interested in comments on the merits of making changes to existing code that works.

© Stack Overflow or respective owner

Related posts about python

Related posts about lambda