how to delete all zeroes from a nested list?

Viewed 337

I wanna delete all zero elements from a nested list. But they are not removed!

FuzzyYesNo_nest=[ ['y', 'y', 'y', 'n', 'n', 'n', 'y', 0, 0, 0, 0, 0],
 ['n', 'n', 'n', 'n', 'y', 'n', 'n']]

for i in FuzzyYesNo_nest:
    try:
        i.remove(0)
    except:
        pass

can u see what is the problem?

4 Answers

If you know the nesting is only one layer deep, you can use this list comprehension:

[[y for y in x if y != 0] for x in FuzzyYesNo_nest]

Example:

FuzzyYesNo_nest=[ ['y', 'y', 'y', 'n', 'n', 'n', 'y', 0, 0, 0, 0, 0], ['n', 'n', 'n', 'n', 'y', 'n', 'n'] ]
print([[y for y in x if y != 0] for x in FuzzyYesNo_nest])

Output:

[['y', 'y', 'y', 'n', 'n', 'n', 'y'], ['n', 'n', 'n', 'n', 'y', 'n', 'n']]

This is because i.remove removes only the first element from the list.

If you look closely at your output, you'll see that one of the zero was removed.

Here is the fixed code for you

FuzzyYesNo_nest=[ 
    ['y', 'y', 'y', 'n', 'n', 'n', 'y', 0, 0, 0, 0, 0],
    ['n', 'n', 'n', 'n', 'y', 'n', 'n']]

for i in FuzzyYesNo_nest:
    try:
        while True:
            i.remove(0)
    except:
        pass

Or you can use nested list comprehension as suggested by @LaytonGB

Keep in mind that the above code will edit the lists in place and list comprehension will create a new copy of your data structure

Use can use a comprehension for each sub list to filter 0:

m = list(map(lambda l: [v for v in l if v != 0], FuzzyYesNo_nest))
>>> m
[['y', 'y', 'y', 'n', 'n', 'n', 'y'], ['n', 'n', 'n', 'n', 'y', 'n', 'n']]

When you use:

for i in FuzzyYesNo_nest:

You aren't iterating through every integer element, but you're iterating through every 1D array in the 2D array:

So your "i"'s would be:

['y', 'y', 'y', 'n', 'n', 'n', 'y', 0, 0, 0, 0, 0]

and

['n', 'n', 'n', 'n', 'y', 'n', 'n']

We can just use a nested loop to do this:

FuzzyYesNo_nest=[ ['y', 'y', 'y', 'n', 'n', 'n', 'y', 0, 0, 0, 0, 0],
 ['n', 'n', 'n', 'n', 'y', 'n', 'n']]

for i in FuzzyYesNo_nest:
    for j in i:
        try:
            i.remove(0)
        except:
            pass

print(FuzzyYesNo_nest)

Resulting output:

[['y', 'y', 'y', 'n', 'n', 'n', 'y'], ['n', 'n', 'n', 'n', 'y', 'n', 'n']]
Related