Pushing all non empty items to the end of a list I have a list like this 

list_ = [" ", " ", "X", " ", " ", "Z", " ", "Y", " "]


I am writing a function that will result in 

list_ = [" ", " ", " ", " ", " ", " ", "X", "Z", "Y"] 


Basically it will push all the non-empty (I'll call " " as empty here for simplicity) to the end of the list while retaining their orders

My solution as follow

def push(list_):
    def find_current_element(list_, from_):
        for i in range(from_+1, len(list_)):
            if list_[i] != " ":
                return i
        return None

    list_ = list_[::-1]
    good_index = list_.index(" ")
    current_element_index = find_current_element(list_, 0)
    while(current_element_index is not None):
        for i in range(good_index, len(list_)):
            if list_[i] != " ":
                list_[good_index], list_[i] = list_[i], " "
                good_index += 1
                current_element_index = find_current_element(list_, current_element_index)
    return reversed(list_)


It works, but it seems too long and using too much resource (reverse the list twice and bunch of for loops). I wouldn't care if the items were just simple character, but I plan to have some big objects as items of the list. I am wondering is there a simpler approach
Your code is incorrect, for example for input [' ', 'X', 'Y'] you get into an infinite loop.

You could just sort by emptiness, which with your apparent definition can be done like this:

&gt;&gt;&gt; list_ = [" ", " ", "X", " ", " ", "Z", " ", "Y", " "]
&gt;&gt;&gt; list_.sort(key=' '.__ne__)
&gt;&gt;&gt; list_
[' ', ' ', ' ', ' ', ' ', ' ', 'X', 'Z', 'Y']


Or more generally (though slower) with a lambda or other self-made function:

list_.sort(key=lambda x: x != ' ')
list_.sort(key=is_non_empty)
list_.sort(key=is_empty, reverse=True)


If you actually had empty strings instead of strings containing a space character, or in general if your objects followed Python's usual thing of empty objects being false and non-empty objects being true, then you could also do this:

list_.sort(key=bool)