# 15. Median syntax issue

#1

Error:
File "python", line 8
elif l == 1:
^
SyntaxError: invalid syntax

Hello all, I'm sure there is something very simple here I am missing, but I am banging my head on my desk! Help?

NOTE: I am just looking for help with this syntax error. if my code will not produce the results for the answer I would prefer to solve it myself. Thanks in advance!!

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

#2

Solved with time. Elif needs to be presented before else.

#3

Shouldn't the median be calculated on the sorted list?

#4

Also, I think you should edit the median calculation for even number of list elements like so:

``````if l % 2 == 0:
median = ((sortx[((l / 2) - 1)] + sortx[((l / 2))]) / 2.0)  # sortx is the sorted list of elements``````

#5

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