Moving specific number (without sort) to the left of list

You can use sorted() with key as bool to achieve this as:

>>> nums = [1, 10, 20, 0, 59, 63, 0, 8, 0]

>>> sorted(nums, key=bool)
[0, 0, 0, 1, 10, 20, 59, 63, 8]

It will work for 0s. In order to make it more generic for any number, you can define key as lambda x: x!=left_num:

>>> left_num = 0

>>> sorted(nums, key=lambda x: x!=left_num)
[0, 0, 0, 1, 10, 20, 59, 63, 8]

As an alternative, here's a less Pythonic (but efficient) version of it using list.count():

>>> nums = [1, 10, 20, 0, 59, 63, 0, 8, 0]
>>> left_num = 0

>>> [left_num]*nums.count(left_num) + [n for n in nums if n!=left_num]
[0, 0, 0, 1, 10, 20, 59, 63, 8]

Here I am finding the count of zeroes in the list (say n), and assigning n zeroes in the start of new list. To get the rest of the unsorted list, I am using list comprehension to filter out the 0s from the list.


output = []
for i in nums:
    if i == 0:
        output.insert(0, 0)
    else:
        output.append(i)
output

sorted(nums, key=lambda i: i != 0)
# or
sorted(nums, key=bool)

Tags:

Python

List