new to python
new to python

Reputation: 29

for statement does not work as intended

so the code is intended to increase the value of count every time it meet the requirement of the if statement and in the end it gives the count of how many times one particular item has appeared in the list, here is the code

x = ["fizz", "fizz", "fizz"]

def fizz_count(x):
    count = 0
    for fizz in x:
        return count+1

now i will only gets me 1 ,for i do aware that the for loop stopped at the very first "fizz" how do i get it going ?(i tried print it return me three one, now that is a start cause if i am able to tell python to check how many one there is i will get the frequency of which the string "fizz" had appeared :)

thank you for anyone who take a look at this

Upvotes: 0

Views: 72

Answers (3)

Tiago Martins
Tiago Martins

Reputation: 79

You could do it too with a lambda:

x = ["fizz", "fizz", "fizz"]
fizz_count = lambda s: sum(1 for match in x if match is s)
print fizz_count("fizz")
# Output: 3

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213193

You are returning from the for loop on the very first iteration, that is why you get count = 1. You should increment the count in loop, and return it at the end of the function.


However, your for loop is not doing what you want it to do. It will not search for fizz in the list. The loop variable fizz will take each element in order from the list, and not just the element with value fizz.

If you want to count the total number of fizz, you need to add an if condition, to test the value. Or you can simply use a generator expression, with sum() function:

def fizz_count(x):
    return sum(1 for item in x if item == "fizz")

Or, even simpler, use list.count(item) method:

def fizz_count(x):
    return x.count("fizz")

Upvotes: 1

jh314
jh314

Reputation: 27802

The issue here is that the return statement will exit out of the function, so you will only loop once, and always return count + 1, which is 0 + 1 = 1.

You can fix this by not returning count+1, but rather by returning the total:

def fizz_count(x):
    count = 0
    for fizz in x:
        count = count+1
    return count

To get the number of times a particular item as appeared, you can use the if statement:

def fizz_count(x, item):
    count = 0
    for fizz in x:
        if fizz == item:
            count = count+1
    return count

Upvotes: 0

Related Questions