1

I want a function called bebo_count that takes a list x as input and returns the count of the string “bebo” in that list. For example, bebo_count(["bebo","buzz","bebo"]) should return 2 i have made a code like this

def bebo_count(x):
    for a in x:
            count = 0
            if a == "bebo":
            count += 1
    return count 

but it doesn't work it's always return 1 to me,can any one please modify this code to be working well?!

1
  • 2
    Once you have your loop working as a learning exercise, consider the code sum(a == "bebo" for a in x) Feb 17, 2014 at 18:54

5 Answers 5

2

You keep resetting count = 0 in your loop, move it outside:

def bebo_count(x):
    count = 0
    for a in x:
            if a == "bebo":
            count += 1
    return count 
0
2

do not reinvent the wheel :-)

There is a built in method count

x = [ "bebo", "bv", "bebo" ]
x.count("bebo")
> 2
x.count("b")
> 0
1

You are setting count = 0 inside the for loop. That means that at each loop iteration, irrespective of what the value of count was before, it gets set back to zero. You should initialize count outside the loop. Note also that I have corrected your indentation.

def bebo_count(x):
    count = 0
    for a in x:
        if a == "bebo":
            count += 1
    return count 

For your reference, here is another way you might write this same function:

def bebo_count(x):
    return len([a for a in x if a == "bebo"])
1
  • 1
    Generally it's better to use generator expressions instead of list comprehensions if you aren't going to reuse the list. So instead of your second example with len([a for...]), I would recommend using sum(1 for a in x if a == 'bebo'), which doesn't create a throw-away list.
    – Dane White
    Feb 17, 2014 at 19:04
0

Your problem is: count = 0 is inside your for loop.

0

To fix your code :

def bebo_count(x):
    count = 0 # initialize the count before you start counting
    for a in x:
        if a == "bebo":
        count += 1
    return count 

However, a more pythonic way could be using list comprehension:

big_list = ["bebo", "something else", "bebo"]
def bebo_count(big_list) :
    return len( [x for x in big_list if x=="bebo" ] )

print( bebo_count(big_list))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.