Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading