HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Removing whitespace and space in list that contains different types of elements

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
spacewhitespaceremovingelementsdifferentthatcontainstypesandlist

Problem

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?

Solution

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')]

Code Snippets

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 != '']
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')]

Context

StackExchange Code Review Q#94471, answer score: 4

Revisions (0)

No revisions yet.