Python sort list with None at the end

python sort list of strings
python sort returns none
python sort list of lists
python sort list of objects
sort vs sorted python
python set sort
python sort lambda
sort array python 3

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

>>> 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.

Python 3 migration: how to properly sort lists containing None , Python 3 migration: how to properly sort lists containing None elements? Hi everyone,. While porting a code base to Python 3, I knew I would get TypeError  You can't sort an array with a single loop. The best you can do is in O(n log n) time. – wvdz Nov 10 '13 at 1:35. remove_val_once is a function I defined that removes the first instance of x in xs @jwodder – user300 Nov 10 '13 at 1:36. Congratulations! you've invented a sorting algorithm that doesn't work!

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.

How to Use sorted() and sort() in Python – Real Python, By the end of this tutorial, you'll know how to: You can use Python to sort a list by using sorted() . sorted(iterable, /, *, key=None, reverse=False) Return a new list containing all items from the iterable in ascending order. The sort function can be used to sort a list in ascending, descending or user defined order. To sort the list in ascending order. List_name.sort () This will sort the given list in ascending order. This function can be used to sort list of integers, floating point number, string and others. numbers = [1, 3, 4, 2]

I created a function that expands on the answer by Andrew Clark and the comment by tutuDajuju.

def sort(myList, reverse = False, sortNone = False):
    """Sorts a list that may or may not contain None.
    Special thanks to Andrew Clark and tutuDajuju for how to sort None on https://stackoverflow.com/questions/18411560/python-sort-list-with-none-at-the-end

    reverse (bool) - Determines if the list is sorted in ascending or descending order

    sortNone (bool) - Determines how None is sorted
        - If True: Will place None at the beginning of the list
        - If False: Will place None at the end of the list
        - If None: Will remove all instances of None from the list

    Example Input: sort([1, 3, 2, 5, 4, None, 7])
    Example Input: sort([1, 3, 2, 5, 4, None, 7], reverse = True)
    Example Input: sort([1, 3, 2, 5, 4, None, 7], reverse = True, sortNone = True)
    Example Input: sort([1, 3, 2, 5, 4, None, 7], sortNone = None)
    """

    return sorted(filter(lambda item: True if (sortNone != None) else (item != None), myList), 
        key = lambda item: (((item is None)     if (reverse) else (item is not None)) if (sortNone) else
                            ((item is not None) if (reverse) else (item is None)), item), 
        reverse = reverse)

Here is an example of how you can run it:

myList = [1, 3, 2, 5, 4, None, 7]
print(sort(myList))
print(sort(myList, reverse = True))
print(sort(myList, sortNone = True))
print(sort(myList, reverse = True, sortNone = True))
print(sort(myList, sortNone = None))
print(sort(myList, reverse = True, sortNone = None))

[Python-Dev] Function to handle None in sort , [Python-Dev] Function to handle None in sort operation, was Re: python 3 niggle: None < 1 raises TypeError. Nick Coghlan ncoghlan at gmail. You can use Python to sort a list by using sorted(). In this example, a list of integers is defined, and then sorted() is called with the numbers variable as the argument: >>> numbers = [ 6 , 9 , 3 , 1 ] >>> sorted ( numbers ) [1, 3, 6, 9] >>> numbers [6, 9, 3, 1]

Sorting HOW TO, You can also use the list.sort() method. It modifies the list in-place (and returns None to avoid confusion). Usually it's less convenient than sorted() - but if you  Python List sort() The sort() method sorts the elements of a given list. The sort() method sorts the elements of a given list in a specific order - Ascending or Descending.

sorted(list) versus list.sort(), sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list. basically says it list.sort: https://docs.python.org/2/tutorial/datastructures.html#​more-on-lists why does it matter if you type in 2.0 vs just 2 at the end of your first return. No, it can be string or None, float and None. Generally, it's homogeneous list with None elements – Nikolai Golub Aug 23 '13 at 20:54

Python Sorting | Python Education, As an alternative to sorted(), the sort() method on a list sorts that The sort() method changes the underlying list and returns None,  Using None as a Null Value in Python. What do you do when None is a valid input object? For instance, what if good_function() could either add an element to the list or not, and None was a valid element to add? In this case, you can define a class specifically for use as a default, while being distinct from None: >>>

Comments
  • Are the values guaranteed to be ints or None, or do you need None to sort after all arbitrary objects?
  • No, it can be string or None, float and None. Generally, it's homogeneous list with None elements
  • @NikolayGolub: For future reference, it's better to make information like that clear in the question—after all, SethMMorton's answer fits what you asked, yet doesn't fit what you actually wanted, so you wouldn't have had a good solution if F.J hadn't happened by.
  • @abarnert I was going by the first sentence, "I have homogeneous list of objects with None", so I assumed that the OP's list was not heterogeneous.
  • @abarnert I see what you are saying. I guess this goes back to the XY discussion we had from a few days ago. I now understand why it's important to ask "Why?".
  • I like this solution, because it fits for all type of homogeneous litst
  • @NikolayGolub: It even supports heterogeneous lists (so long as your heterogeneous types are all comparable in the first place, of course).
  • If using reverse=True with this solution, use x is not None in the key, otherwise all None values are returned first.
  • @tutuDajuju You don't need tuples with True and False in the first place if you want to sort by descending value and None last. You can simply do sorted(l, reverse=True) for [7, 5, 4, 3, 2, 1, None] as seen in the original question.
  • WOW! I didn't know about this "inf" awesome!
  • This doesn't work if the list contains infinities or if the list is a list of strings.
  • @NeilG Yes, we covered that in the comments to the question itself. This answer was for the question as it was originally posted, but will still work for integers only so I didn't delete it.
  • When your function gets that large, why not break it out into a proper function definition? Leaving it as a lambda just makes it hard to read.