Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get list if contains non zero element

Tags:

python

list

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 !

like image 974
sam Avatar asked Dec 05 '25 07:12

sam


1 Answers

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.

like image 160
Abdou Avatar answered Dec 07 '25 19:12

Abdou