# Median - Is my code unnecessarily complex?

#1

``````def median(lst):

new_lst = sorted(lst[:])

if len(lst) % 2 == 0:
while len(new_lst) > 2:
new_lst.remove(new_lst[0])
new_lst.remove(new_lst[-1])
return ((new_lst[0] + new_lst[1]) / 2.0)

else:
while len(new_lst) > 1:
new_lst.remove(new_lst[0])
new_lst.remove(new_lst[-1])
return new_lst[0]``````

#2

Looks good to me, if it works it works.

I do like how you did it though, but yea you waste some CPU cycles doing unnecessary things. It will only matter when you start to work on huge data sets so don't worry about it.

Also here is a fancy sample,

``````def median(lst):
return sorted(lst)[len(lst) / 2] if len(lst) / 2 == 1\ # Line break
else float(sorted(lst)[len(lst) / 2] + sorted(lst)[len(lst) / 2-1]) / 2``````

As you can see you can make it shorter but not necessarily easier to understand. There are other one liners too but that will come with practice.

#3

Thanks. I'm trying to do each exercise how I first think of it and then see how others approached it in the Q&A. I felt like mine was wasteful.