Reputation: 31
How to make this code into a one-liner? The list contains only 0 and 1
val = 0
for item in list:
if item == 0:
val += 1
Upvotes: 0
Views: 103
Reputation: 780724
Use the sum()
function along with a generator expression.
val = sum(1 - item for item in list)
or
val = sum(0 == item for item in list)
or you can use a conditional in the generator
val = sum(1 for item in list if item == 0)
Upvotes: 2