Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list while pushing None values to the end

I have a homogeneous list of objects with None, but it can contain any type of values. Example:

>>> l = [1, 3, 2, 5, 4, None, 7] >>> sorted(l) [None, 1, 2, 3, 4, 5, 7] >>> sorted(l, reverse=True) [7, 5, 4, 3, 2, 1, None] 

Is there a way without reinventing the wheel to get the list sorted the usual python way, but with None values at the end of the list, like that:

[1, 2, 3, 4, 5, 7, None] 

I feel like here can be some trick with "key" parameter

like image 570
Nikolai Golub Avatar asked Aug 23 '13 20:08

Nikolai Golub


People also ask

Can you sort a list with none in it?

sort() doesn't return any value while the sort() method just sorts the elements of a given list in a specific order - ascending or descending without returning any value. So problem is with answer = newList. sort() where answer is none. Instead you can just do return newList.

How do you sort a list without altering the content of the original list?

If you want to create a new sorted list without modifying the original one, you should use the sorted function instead. As you can notice, both sort and sorted sort items in an ascending order by default.

How do you sort a list in reverse order?

sort() method. This method requires two parameters i.e. the list to be sorted and the Collections. reverseOrder() that reverses the order of an element collection using a Comparator. The ClassCastException is thrown by the Collections.

What happens when sort () is used in a list?

sort() Return Value The sort() method doesn't return any value. Rather, it changes the original list. If you want a function to return the sorted list rather than change the original list, use sorted() .


2 Answers

>>> l = [1, 3, 2, 5, 4, None, 7] >>> sorted(l, key=lambda x: (x is None, x)) [1, 2, 3, 4, 5, 7, None] 

This constructs a tuple for each element in the list, if the value is None the tuple with be (True, None), if the value is anything else it will be (False, x) (where x is the value). Since tuples are sorted item by item, this means that all non-None elements will come first (since False < True), and then be sorted by value.

like image 115
Andrew Clark Avatar answered Sep 23 '22 03:09

Andrew Clark


Try this:

sorted(l, key=lambda x: float('inf') if x is None else x) 

Since infinity is larger than all integers, None will always be placed last.

like image 41
SethMMorton Avatar answered Sep 21 '22 03:09

SethMMorton