Removing whitespace and space in list that contains different types of elements My goal is to remove whitespaces from string elements of my list, and to remove empty string elements altogether. My code:

def modifylist(lst):
        lst = [elt.strip() if type(elt) is str else elt for elt in lst]
        while '' in lst:
                lst.remove('')
        return lst


Is there any other method that python provides? more elegant and hopefully more fast than using this while loop?
Some suggestions


Follow pep8
Use duck-typing.  So, for example, use elt.strip() if hasattr(elt, 'strip')
It will be much more efficient to filter items in another list comprehension, since it only requires one search through the list rather than many.
The simplest approach would probably be to change the first list comprehension to a generator expression, then feed that to a list comprehension that filters out empty strings.
This could conceivably be a single list comprehension, but I think it would be too verbose.  Further, it would require stripping twice.


So I would do something like this:

def strip_list_noempty(mylist):
    newlist = (item.strip() if hasattr(item, 'strip') else item for item in mylist)
    return [item for item in newlist if item != '']


You could also duck-type the filtering, like so:

def strip_list_noempty(mylist):
    newlist = (item.strip() if hasattr(item, 'strip') else item for item in mylist)
    return [item for item in newlist if item or not hasattr(item, 'strip')]