Summing the 1s from a list in python

Given I have the task that I have to count the number of 1s entailed in a list. Upon assessing the prior my code is giving the message "NONE."

What am I doing wrong ?

#alternative: 
result=[]

def count(x):
    for i in enumerate(x):
        if i==1:
            sum(i)
            append.result(i)
            return result 

c = count([1, 4, 5, 1, 3])
print(c)

        
    

>Solution :

You probably want it like this:

result=[]

def count(x):
    for i in x:
        if i==1:
            result.append(i)
    return len(result) 

c = count([1, 4, 5, 1, 3])
print(c)

Output

2'

Or you could simplify it further by:

def count(x):
    result = 0
    for j, i in enumerate(x):
        if i==1:
            result +=1
    return result

Or, if you want to use pandas, you can write it even more simple:

import pandas as pd

def count(x):
    x = pd.Series(x)
    return x.value_counts().loc[1]

Leave a Reply