An student
An student

Reputation: 392

removing list with all values 0 from multidimensional list in python

a= [[0,0,0,0],[1,2,3,4],[5,6,7,8],[0,0,0,0],[0,0,0,0],[10,20,30,40],[0,0,0,0]]
for i in a:
    if all([ v == 0 for v in i]):
        a.remove(i)
print(a)

The output it gives is

 [[1,2,3,4],[5,6,7,8],[10,20,30,40],[0,0,0,0]]

I don't figure out why it is not removing the last list with values zeros.

Upvotes: 1

Views: 165

Answers (2)

cs95
cs95

Reputation: 402854

You're missing a tiny detail - you'll need to iterate in reverse.

for i in reversed(range(len(a))):
    if all(v == 0 for v in a[i]):
        del a[i]

print(a)
[[1, 2, 3, 4], [5, 6, 7, 8], [10, 20, 30, 40]]

By iterating forward, you're shrinking the list in size, so the loop never ends up iterating over the list completely (since you shrunk the list).

Upvotes: 1

KBN
KBN

Reputation: 153

The below code would help

new_a = [l for l in a if set(l) != {0}]

Upvotes: 0

Related Questions