-1

How do you get the number of times the number 1 appears in the following list:

list = [1,2,3,4,5,1,1]

I have tried the following and it works, but I want to do it without creating an empty list and the if statement, but what I really want is a count of the number of times 1 appears instead of a list with only 1s and then count them.


list = [1,2,3,4,5,1,1]

list_1s = []

for i in list:

    if i == 1:
       list_1s.append(i)

    else:
       pass


n_1s = len(list_1s)

print(n_1s)


1 Answers1

1

lst = [1,2,3,4,5,1,1]

Using list comprehensions to solve it -

count_1s = len([i for i in lst if i==1])
print(count_1s)
    3
cph_sto
  • 7,189
  • 12
  • 42
  • 78