Sorting a list/array odd numbers first, then even numbers in Python

I want to sort a list in Python3, first odd numbers, then even numbers.
Let the list is li = [4, 1, 5, 8, 2, 9, 3, 10, 7, 6]
Output should be: 1 3 5 7 9 2 4 6 8 10
How to solve this using function or lambda or any other way?

#Edited
using lambda only.


Solution 1:

You're effectively sorting on two keys: the primary key is whether the int is even or odd, and you want odd to compare "smaller". The secondary key is then the integer itself. That can all be expressed by sorting on tuples of (primary key, secondary key), which can be expressed by building those tuples straightforwardly via a function passed to sorting's optional key= argument:

>>> li = [4, 1, 5, 8, 2, 9, 3, 10, 7, 6]
>>> sorted(li, key=lambda i: (1 - (i & 1), i))
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

Alternative: in any case where you're sorting on N keys, instead of doing a single sort with N-tuple keys, you can instead do N sorts on the individual keys, least-significant key first. This may well not be obvious, and relies on that Python's sorting algorithm is "stable" (preserves the input order of items that compare equal). Concretely, for the case at hand, here's one way to do that:

>>> sorted(sorted(li), key=lambda i: i % 2, reverse=True)
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

For reasons that are uncomfortably involved, it can be faster to do it this way. Despite that you're doing more sorts, it's possible that cheaper comparisons can more than make up for that.

Solution 2:

We take the list, filter only the odd values, sort, and splat the values and do the exact same but for evens.

li = [4, 1, 5, 8, 2, 9, 3, 10, 7, 6]
final_li = [*sorted(filter(lambda x: x % 2, li)), *sorted(filter(lambda x: x % 2 == 0, li))]