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:
val+=1
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):
val=0
for i in range(len(list1)):
if list1[i]==obj:
val+=1
print(i)
else:
print(str(i) +'else')
return val
count(['a','b','c','a','a'],'a')
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.