# Median

#1

Hey guys , i was trying to solve the median problem the code seems to me to be correct but still getting an error message ! ,i can find out where is my mistake any help pls !
here is my code

def median(x):
new=sorted(x) # new sorted lis
median=0 # variable initiated to 0 to store the medium
if len(new) %2==0:
median+= (new[len(x)//2.0]+new[(len(x)//2.0)-1])/2.0
else:
median+=new[len(x)//2.0]

``return median``

where is the mistake ?
thanks !!

#2

In your solution, the following code would be executed:

``````if len(new) % 2 == 0:
return (new[len(x) // 2.0] + new[(len(x) // 2.0) - 1]) / 2.0
else:
return new[len(x) // 2]``````

This is improper due to the fact that a list cannot accept a float as an index; it must be an integer value. The following error is produced:

``TypeError: list indices must be integers, not float.``

Instead, you'll want to remove the decimal from these values as to interpret them as integers. Keep in mind that you'll still want to return the final value as a float.

Additionally, I see no reason why the median value can't simply be returned, instead of storing as a variable, since no other modification needs to be made. (This isn't necessary for the code to validate, however.)

## Modified Code:

``````def median(x):
new = sorted(x)
if len(new) %2 == 0:
return (new[len(x) // 2] + new[(len(x) // 2) - 1]) / 2.0
else:
return new[len(x) // 2]``````

#3

thanks matt !!! i get my error now it all clear
code well !