Median returns [1] instead of 1


Hi, I'm stuck here, because the func returns [1] instead of 1

my code:

I get the error "Oops, try again. median([1]) returned [1] instead of 1"

Here's my code. I even added an elif for the median([1]) and still gives this error:

def median(numbers):
    my_list = []
    for n in range(len(numbers)): #ERROR
        for x in numbers:
            if x == min(numbers) and len(numbers) > 1: 
            elif len(numbers) == 1:
    return my_list
    m = len(my_list)
    if m % 2 == 0:
        return my_list[((m/2) + (m/2 - 1)) / float(2)]
    elif m == 1:
        return my_list[0]
        return my_list[((m+1)/2) - 1] 
print median([1, 4, 2, 7, 5, 3, 9])


p.s. I used my own code instead of sorted() and I've verified it worked for every input


Can you format your code? it will be helpful to solve your problem!



Eighteen lines of code to find the middle one or two elements in a sorted list is a bit mighty, would you agree? When a small problem becomes complex code, it becomes a big problem, transforming the problem and the solution. This is counter productive, to say the least.

Scratch what you have. Nobody is going to analyze it. It's too far fetched. Start over.

What is the given? => A sample space

What is the constraint? => Sample space is sorted

What is the objective? => The middle one (data point) or average of middle two, by parity

This does not take a lot of logic to perform. Give it another go and see if you don't reduce your code substantially.


Given a list that we care nothig about in the global scope, we can sort in place the input.


The single object came in, and now goes through a simple transformation. But whatever object that may have been, unless the argument was a list literal, it too will undergo the same transformation. Lists are reference objects that do not get copied to functions, only referenced. If the list was indeed a defined object, it just got sorted.

That all aside, we now have an iterable object with a length. We know that it has order from lowest to highest. The median is right at hand.

n = len(x)

m = int(n / 2)

m will be the middle index, or the index of the lowest value of the top half.

return x[m] if n % 2 else float(x[m - 1] + x[m]) / 2


firstly you can use a.sort() to sort the list a,
In first case code should be
if m % 2 == 0:
return my_list[((m/2) + (m/2 - 1))] / float(2)


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