sam
sam

Reputation: 19164

get list if contains non zero element

I have a list.

l1 = [0, 0, 2, 0]
l2 = [0, 0, 0, 0]

I want to print list if list contains non zero element in it.

Output:

If one one list passed, then only list with non zero element will get printed. In example above only l1 will get printed.

[0, 0, 2, 0]

I want to know how efficiently it can be done. Thanks !

Upvotes: 2

Views: 4228

Answers (5)

yinnonsanders
yinnonsanders

Reputation: 1871

Answered in the comments, but I'll post it as an answer:

for l in filter(any, (l1, l2)):
    print(l)

The combination of filter and any makes it so the print only executes for lists with non-zero elements. any returns False as soon as the first non-zero (or truthy) value is encountered. For integers, 0 is the only i for which bool(i) is falsey.

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78556

You can use the built-in any to test if the list contains at least one non-Falsy/non-zero element.

Zero is falsy, in fact the only falsy number:

>>> bool(0)
False

So you can easily do:

for lst in (l1, l2):
   if any(lst):
      print(lst)

This would provide correct results as long as your lists contains only numericals and you're not willing to make an expcetion of non numericals.

Upvotes: 1

Abdou
Abdou

Reputation: 13274

Use any on your lists:

for lst in (l1, l2):
    if any(lst):
        print(lst)

You can also use all:

for lst in (l1, l2):
    if all(x != 0 for x in lst):
        print(lst)

I hope this helps.

Upvotes: 2

Ersel Er
Ersel Er

Reputation: 771

You can try this:

lists = [[0, 0, 0, 0],[0, 0, 2, 0]]
for l in lists:
    if set(l)=={0}:
        pass
    else:
        print l 

Upvotes: 1

Megabeets
Megabeets

Reputation: 1398

You can use the built-in function any():

From Python's documentation:

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

Here's a code:

for l in [l1,l2, ..., ln]:
    if any(l):
        print(l) 

Upvotes: 1

Related Questions