Pushing all non empty items to the end of a list
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)