'TypeError: '<' not supported between instances of 'NoneType' and 'int'. Anyone knows why is that?

Here's the code.

digs = (-10, 0, 7, -2, 3, 6, -8)

def sort(x):
    if x < 0:
        return False

print(sorted(digs, key=sort))

When launched the following error appears. Can anyone explain why?

I figured it out that I can do this:

def sort(x):
    return x >= 0

and it's gonna work fine. But I still don't get why that error shows up when comparing x and 0.



Solution 1:[1]

In your first version:

def sort(x):
    if x < 0:
        return False
    # but then what happens if x >= 0?
    # if the code reaches this point, the function will return None

In the second version of your sort function, a boolean value is always returned. This avoids the error of comparing None to something.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hbgoddard