Count function solution

Screen Link:

My Code:

def count(list1,obj):
    for val in list1[val]:
        if list1[val]=obj: 
    return val

What I expected to happen:

What actually happened:

  File "<ipython-input-1-5b7fc889f5dd>", line 3
    if list1[val]=obj:
SyntaxError: invalid syntax

Why is this answer incorrect, please.

missed adding ‘return val’ statement inside function
same error is returned though

Hi @piya,

The error that you are getting is because you are comparing list1[val] and obj using =. The single equality sign is used to assign a value to a variable.

To compare two variables, you need to use a double equality sign: ==.

In your case, it would be:

def count(list1,obj):
    for val in list1[val]:
        if list1[val]==obj: 
    return val



Thanks so much Francois. I’m finding this community so helpful.

I re-wrote the function this way:It works but I’m intrigued that i is printed 0,1,2,3,4 then again 3.
Why would i go back 1 in the end please?

def count(list1,obj):
    for i in range(len(list1)):       
        if list1[i]==obj: 
            print(str(i) +'else')           
    return val


It does not go back 1. The 3 that you see is the result of count(['a','b','c','a','a'],'a'). In a Python script, if the last line results in a value that is not stored anywhere, this value gets printed.

If you replace the last line by result = count(['a','b','c','a','a'],'a') then the 3 will be stored in result instead of being printed.

1 Like