1

I am still a bit of a beginner, and I can't figure out a good way to crack this nut.

I have a nested list of arbitrary depth. Something like :

sample = [[1, [2, '', [None, 5], [6]]], None]

I need to cycle through each level of the list and remove any entries that are empty strings or None. Aside from this, the nested list should be unchanged.

I suspect something like recursion, but I've never created a function that does that, nor can I find a good example online that fits my needs. My attempts have been utterly ineffective.

Any help would be appreciated, as I am at a bit of a loss how to even start.

0

2 Answers 2

1
def filter_null(l):
    l = l.copy()
    i = 0
    while i < len(l):
        if isinstance(l[i], list):
            l[i]= filter_null(item) # this is the recursion
        if not item: # Checks if item evaluates to False or None
            l.pop(i)
            i -= 1 # If you delete this line the following item will be skipped
        i += 1
Sign up to request clarification or add additional context in comments.

Comments

0

You can use recursion:

sample = [[1, [2, '', [None, 5], [6]]], None] 
def rem_vals(r):
   return [rem_vals(i) if isinstance(i, list) else i for i in r if i not in [None, '']]

print(rem_vals(sample))

Output:

[[1, [2, [5], [6]]]]

4 Comments

This only considers None and '' and also if something like [None] showed up, it would erase None from the list but keep the empty list. e.g.: rem_vals([1, [None], 3]) -> [1, [], 3]
@RafaelSetton The OP only specified None and '' as the filter criteria. Simply checking for value truthiness if not i is not very thorough, as it would also remove 0 and any other object whose truthiness evaluates to False
in that case the way you filtered is correct, but the empty list would still remain as I pointed out earlier
@RafaelSetton, which is what the OP requested.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.