Liam Barmaimon
Liam Barmaimon

Reputation: 31

Python one-liner with if

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

Answers (2)

Avo Asatryan
Avo Asatryan

Reputation: 414

I would suggest you:

val = list.count(0)

Upvotes: 6

Barmar
Barmar

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

Related Questions