Two versions of code. Can't spot the difference but gives different results!

Hello all!

First post. I was doing the lists advanced code challenge and was quite pleased to have worked out what I need to do on my own. The way the code should be written that I came up with matched the way the code was written in the Code Academy solution. However when writing the code, I have written it in a slightly different way to the solution code. To my eyes they should do exactly the same thing but when I run the function with a list as the argument, my code gives the wrong answers or an index error and I can’t figure out why or what is different between our codes to produce the wrong result for my version? See below, my code is on the right.

To my eyes, even though written slightly differently they should be exactly the same or at least I can’t figure out where the bug in my code lies. Thanks in advance for the help!

In lines 7, 8 (your codes), a and b hold actual values, not indexes, sum up a and b in line 9 and it should work fine.

def middle_element(lst):
    if len(lst) % 2 == 0:
        a = lst[int(len(lst)/2)]
        b = lst[int(len(lst)/2) - 1]
        return (a + b) / 2
    else:
        return lst[int(len(lst)/2)]
3 Likes

Ahh ■■■■ I see what I’ve done, thanks. Forgot a and b are the elements/values already. Literally staring me in the face.

Thanks very much joelmiller big help!

1 Like