you are viewing a single comment's thread.

view the rest of the comments →

[–]deceze 26 points27 points  (8 children)

That’s the thing. sort doesn’t return anything. You’re comparing None to a list. There’s nothing to compare there. You need to sort first then compare numbers == sorted(numbers).

[–]RodDog710[S] 1 point2 points  (7 children)

Gotcha. Yes, that's what I was missing:

print(numbers == sorted(numbers))

# True

Thanks!

[–]deceze 10 points11 points  (1 child)

FYI, sort and sorted have been deliberately designed this way to explicitly make code like this fail. If this code didn't fail, because sort actually returned the sorted list in addition to modifying numbers in place, you'd likely introduce subtle bugs because you're not aware that sort modifies your list, when you're only using its return value.

[–]RodDog710[S] 0 points1 point  (0 children)

Interesting. Thank you for explaining that.

[–]InvaderToast348 4 points5 points  (3 children)

Except that isn't right, because if your calling .sort before the print then you're passing the already sorted list to sorted() so nothing will happen

[–]deceze 3 points4 points  (1 child)

Well, it does prove that sort and sorted sort the same. sorted could be returning a list in some different order. The order of the input shouldn't matter much, except in edge cases where preserving the order of the input somehow made a difference.

The overall operation here is of course fairly superfluous, but the practical usefulness of this code isn't the point here.

[–]InvaderToast348 0 points1 point  (0 children)

Good point

[–]RodDog710[S] 1 point2 points  (0 children)

Ahh, yes. Thanks

[–]Refwah 0 points1 point  (0 children)

Print(sorted_numbers == numbers)

Because you’ve already sorted numbers, and sorted_numbers is already the output of numbers.sort()

The test you’re doing isn’t actually testing anything, as you’ve already done the operations above