Lorenzo
Lorenzo

Reputation: 107

How to sort a list by key with None type elements?

I have a list where some elements are None type. I need to sort this list, but I receive this error because None evidently can't be sorted.

Traceback (most recent call last):
  File "<stdin>", line 9, in <module>
    random.sort(key=takeSecond)
TypeError: unorderable types: int() < NoneType()

This is an example program:

# take second element for sort
def takeSecond(elem):
    return elem[1]

# random list
random = [(2, None), (3, 4), (4, 1), (1, 3)]

# sort list with key
random.sort(key=takeSecond)

# print list
print('Sorted list:', random)

How can I solve this issue sorting the other elements and maybe put None types at the end of the list?

EDIT: Thanks for all the answers, and if the list contains strings instead of int?

Upvotes: 0

Views: 963

Answers (2)

Thomas Ruble
Thomas Ruble

Reputation: 952

Try this for your key function:

import math

def takeSecond(elem):
  return elem[1] if elem[1] is not None else math.inf

Upvotes: 1

abc
abc

Reputation: 11929

You can manage the case of None by assigning a high value to it, e.g, float('inf').

>>> lst = [(2, None), (3, 4), (4, 1), (1, 3)]
>>> lst.sort(key=lambda x:x[1] if x[1] is not None else float('inf'))
>>> lst
[(4, 1), (1, 3), (3, 4), (2, None)]

Upvotes: 2

Related Questions