I\'m trying to sort a list of objects using
my_list.sort(key=operator.attrgetter(attr_name))
but if any of the list items has attr = None
attr = None
The solutions proposed here work, but this could be shortened further:
mylist.sort(key=lambda x: x or 0)
In essence, we can treat None as if it had value 0.
E.g.:
>>> mylist = [3, 1, None, None, 2, 0] >>> mylist.sort(key=lambda x: x or 0) >>> mylist [None, None, 0, 1, 2, 3]