4
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Some suggestions

  1. Follow pep8
  2. Use duck-typing. So, for example, use elt.strip() if hasattr(elt, 'strip')
  3. 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.
  4. 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.
  5. 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')]
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.