Problem with Median


I wrote my code for the Median - Practice makes perfect section, and kept getting errors in the editor and messages saying that I was returning the wrong information from the class. When I run the code directly in Python 3 it works without any problems. Could you tell what I’m doing wrong with the following code?

def median(x):
    list = sorted(x)

    if len(list) % 2 == 0:
        first = round(len(list)/2)
        second = first - 1
        return ((list[first] + list[second]) / 2)
        dig = round(len(list)/2)
        return list[dig]

Thank you


Even if it appears to work, it is never a good practice to name variables the same as the class name. list is a reserved word, and name of a built-in function.

The indentation of else looks to be off.


Thanks. Didn’t realize list was a reserve word.

I had to manually add the indents into the forum editor, as it removed them when I just copied/pasted the code into it.


Select the code then click the </> button in the tool bar.

Notice that it is highlighted in your edited OP?


Great tip. Thank you


Let’s pretend your variable is sample

return (sample[first] + sample[second]) / 2

Python 2 will return an integer, so we need to declare the sum as a float…

 return float(sample[first] + sample[second]) / 2


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.