0

In python,

sorted(["a", "b", None])

produces

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-37-2c38da1a26e5> in <module>
----> 1 sorted(["a", "b", None])

TypeError: '<' not supported between instances of 'NoneType' and 'str'

I can write something hacky like

def sort_with_none(my_lst):
    if None not in my_lst:
        result = sorted(my_lst)
    else:
        result = (
            sorted([xx for xx in my_lst if xx is not None])
            + [xx for xx in my_lst if xx is None]
        )
    return result

And then calling

sort_with_none(["a", "b", None])

works fine. But I assume there's a slicker way to do this. Any advice?

dslack
  • 835
  • 6
  • 17
  • 3
    Hmm, looks like this question basically answers mine: https://stackoverflow.com/questions/18411560/python-sort-list-with-none-at-the-end – dslack Jan 17 '21 at 09:02

1 Answers1

1

simple solution is use key option

sorted(["a", "b", None], key=lambda x: x or '')
Brown Bear
  • 19,655
  • 10
  • 58
  • 76