Non-zero elements of a list in Python

I have a list J. I want to identify number of non-zero elements and divide by 12 and then multiply by 100. But I get an error. I present the expected output.

J=[[1, 4, 0, 0, 0, 9, 0]]
Percent_Unvisited=(len(J[0]!=0)/12)*100
print(Percent_Unvisited)

The error is

in <module>
    Percent_Unvisited=(len(J[0]!=0)/12)*100

TypeError: object of type 'bool' has no len()

The expected output is

25

>Solution :

You can use a generator expression with sum to count the number of elements that are non-zero. This works because True and False are equivalent to 1 and 0, respectively, when used in arithmetic.

Percent_Unvisited = sum(x != 0 for x in J[0]) / 12 * 100

Leave a Reply