# Non-zero elements of a list in Python

## Question:

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
``````

The error is occurring because the != operator has higher precedence than the indexing operator [0]. This means that the expression J[0]!=0 is evaluated first, which returns a boolean value (True or False), and then you are trying to get the length of this boolean value, which is not possible.

To fix this, you can add parentheses to ensure that the indexing is done before the comparison:

``````J=[[1, 4, 0, 0, 0, 9, 0]]
percent_unvisited = (len([x for x in J[0] if x != 0])/12)*100
print(percent_unvisited)
``````

Here, we use a list comprehension to count the number of non-zero elements in the list J[0], and then divide by 12 and multiply by 100 to get the percentage. The output will be 25.0, which you can format as an integer if you don’t need the decimal places.

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
``````
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.