k.dog k.dog - 3 years ago 129
Python Question

Function to count the the position of the first occurrence of item ‘y’ in sequence ‘z’

enter image description hereWe need to make a function that takes a list

and returns the index at which
first occurs. For example, if it's the second item in the list it will return
, etc. We only use
if else
statements and boolean values.

My function is working for all the number values I have been given, however when I put in a string as a list it only returns me one.

def positionfirst(z,y):
for item in y:
if z!=item:
if val==len(y):
return None
return val

Answer Source

Your picture shows your error:

print((positionfirst('d', ['abcdefg'])))

Will return 0, as 'd' != 'abcdefg', which is the only element in ['abcdefg']. You probably want

print((positionfirst('d', 'abcdefg'))).

This way the for loop iterates over the chars in the string. You can add a


in your loop, to see what is happening. The first version will give


the second


Those are the items you will compare against. Finally a bit shorter version of your function:

def positionfirst(z, y):
    val = 0
    for item in y:
        if z == item:
            return val
        val += 1
    return None
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download