Python: Minimum element by attribute

Posted by Moser on 02 Mar 2017

Suppose you want an element from a list that is minimal in a certain respect. The code you usually see for this is:

import collections
Item = collections.namedtuple("Item", "id cost")
items = [Item(1, 10.00), Item(2, 200), Item(3, 1.0)]

sorted(items, key=lambda item: item.cost)[0]
# Item(id=3, cost=1.0)

Here is a nicer way to do this using the standard library:

min(items, key=lambda item: item.cost)
# Item(id=3, cost=1.0) 
# or even
import operator as op
min(items, key=op.attrgetter("cost"))
# Item(id=3, cost=1.0)

This is not only more elegant, but also more efficient because sorting a list is more time consuming than finding the minimal element. When dealing with generators this method uses a lot less memory.

blog comments powered by Disqus