Search code examples
pythonlistredditeditingpython-re

How can I remove empty lists from within another list?


After running text through this code:

import re


def text_manipulator(text):
    paras = re.split('\n|\n ', text)
    item_number = 0
    for item in paras:
        item_replace = re.split('(?<=[.!?]) +', item)
        paras[item_number] = item_replace
        item_number += 1
    fixed_paras = [x for x in paras if x]
    return fixed_paras

I'm left with this.

[["Not a postal worker, but I'm good friends with the one on my route,"], [''], ['He has helped me through some tough times (just a nice guy to talk to)'], [''], ['I often offer him a cold gallon of water or a energy drink, he seems to really enjoy.', 'He is a real down to earth guy.']]

What can I do differently to be left with this?:

[["Not a postal worker, but I'm good friends with the one on my route,"], ['He has helped me through some tough times (just a nice guy to talk to)'], ['I often offer him a cold gallon of water or a energy drink, he seems to really enjoy.', 'He is a real down to earth guy.']]

Thanks in advance


Solution

  • According to the docs for any(iterable):

    Return True if any element of the iterable is true. If the iterable is empty, return False.

    Hence when a list of Strings is passed to Any and if all of the elements in list are empty strings then it will return False as Empty String is equivalent to False.

    So in your code replacing the second last line with:

    fixed_paras = [x for x in paras if any(x)]
    

    will eliminate the lists with empty strings too.

    Note: This answer is based on juanpa.arrivillaga's comment