 # FAQ: Learn Python - Practice Makes Perfect - median

This community-built FAQ covers the "[median](
https://discus…icates/330718

)" exercise in Codecademy’s lessons on Python.

## Join the Discussion. We Want to Hear From You!

Have a new question or can answer someone else’s? Reply ( ) to an existing thread!

Agree with a comment or answer? Like ( ) to up-vote the contribution!

Want to take the conversation in a totally different direction? Join our wider discussions.

Found a bug? Report it!

Have a question about your account, billing, Pro, or Pro Intensive? Reach out to our support team!

None of the above? Find out where to ask other questions here!

Not seeing your question? It may still have been asked before – try ( ) in the top-right of this page. Still can’t find it? Ask it below by hitting the reply button below this post ( ).

## Other FAQs

• This list will contain other frequently asked questions that aren’t quite as popular as the ones above.
• This FAQ is built and maintained by you, the Codecademy community – help yourself and other learners like you by contributing!

2 posts were split to a new topic: PyCharm Gives a Different Result than Codecademy

Hello - Could someone help me out and explain why my code isn’t working? The console says “median() returned 0.0 instead of 1”. I’m not sure why this happening since I’m returning the list when the length of the list is a single digit, not the float for average later on in the function.

Any help is appreciated.

Thanks.

``````def median(lst):
lst = []
avg = float(0)
sortedlst = sorted(lst)
middle = len(sortedlst) / 2
if len(lst) == 1:
return lst

elif len(lst) > 0:
return lst[middle]
if middle % 2 != 0:
avg = lst[middle] + lst[middle-1] / 2
return avg
``````

my code is working, but i think its a bug- at the 3rd line from the bottom ,“median_place = (sort_len /2) + 0.5”, ive changed it from (-0.5) to +0.5 cause i got an error for the list [2,6,8,12,23]. when its written like that it means “median_place = (5/2) + 0.5 = 3”. that will result the index for list == 12, instead of list  == 8. can someone help me understand why?

# i hope i was clear, im not an english native speaker

def median(whatev):
sort = sorted(whatev)
sort_len = len(sort)
if sort_len == 1:
return sort
else:
while sort_len > 1:
if sort_len % 2 == 0:
before_place = (sort_len / 2) -1
before = float(sort[before_place])
after_place = before_place + 1
after = float(sort[after_place])
med_even = float((after + before) / 2)
return med_even
else:
median_place = (sort_len /2) + 0.5
median2 = sort[int(median_place)]
return median2

Today someone told me that they didn’t care what their code looked like, how verbose and repetitive it was, how spaghetti-like it was, as long as it worked. They were confident it did so that ended the discussion. A learning experience was lost. Let’s hope the same is not in store here else I’ll be Oh-and-Two for the day.

One cannot believe this code runs, but if it does, kudos to you for getting such a complex engine moving at all. There is so much code there I don’t know where to begin analyzing.

This is not a mammoth task, and should not take more than a few lines of code to perform.

The median is the middle value of a sorted, odd length list, called a sample. If the sorted sample has an even length then the median is the average of the middle two terms.

There are hints of this in the code, but a whole lot of other stuff that seems to be doing all kinds of things. Forgive us if we appear a bit overwhelmed. Could you simplify and reduce so we are not made so weary?

thank you for your reply. i dont know about simplifying the code, if you have pointers i would love to read about it, but my question refers to the last “else” block -that block refers to the case of an odd length of list, the middle value is the median. lets say the length is 7 - the index of the 4th value it is right? well, originally ive written that part like so:

else:
median_place = (sort_len /2) - 0.5
median2 = sort[int(median_place)]
return median2

as “sort” is the list name for the sorted list, that will give us:

median_place = (7/2) - 0.5 = 3
medien2 = sort[int(3) = index of 3 in the list = the 4th value in a list of 7 values.

but that resulted in an error. only when i changed the first line to:

median_place = (sort_len /2) + 0.5

the code worked fine, but this will give us the index of 4- the fifth value in the list. and that is what i dont understand. can you please help me?

Recall that for an odd length list, there are equal number of elements on either side of the median…

``````      => sorted list
^
median == 4
``````

and for even length lists to balance out the same way, we need a pair of elements as the median…

``````      => sorted list
^
median == float(4 + 5) / 2
``````

One goal of simplification is reduction and ellimination of repetition.

Your first line in the earlier example is an good first step… Cache the length. For simplicity we can use `n` as our variable (it’s less verbose).

Unfortunately it’s beyond that point that things come off the rails by overcomplicating the problem.

Given a list, we’ll call it, `sample`, our first step is to sort it, which we cache as a separate list so as not to modify the original order, along with the length.

``````s = sorted(sample)
n = len(s)
``````

I used simple variable names because their definitions are very clear, and right in the code. We have only to look up and see what values they represent without going into verbose detail.

Finding the middle of the list involves simple integer division…

``````m = n // 2
``````

Consider a list with length 1. What will `m` be? Answer, `0`. This means we do not have to test if the length is one, just return the value at that index… `s`. This still does not take an extra step as it fits right into the pattern of any odd length list median.

``````if n % 2: return s[m]    # read as `if n MOD 2 is non-zero`
``````

So in four lines of simple code we have returned the median for all odd length lists.

The final step will involve only even length lists. Here is where we need to take a careful look at the value of `m`.

`````` 0  1  2    3  4    5  6  7   => indexes
    
^
median
``````

What is the value of `m` for the above list?

``````8 // 2  =>  4
``````

Now look where index 4 is in the above? It is the right side of the middle pair, meaning the other member is to the left of that, meaning `m - 1`. So,

``return float(s[m - 1] + s[m]) / 2``

This doesn’t seem to work anymore.
I’m even printing all the variables to debug.

The list S is [4, 4, 5, 5].
The median M is 2.
So S[M-1] is 4, and S[M] is 5.
All those variables print correctly.

But:
return (s [m - 1] + s [m]) /2 --> returns 4
return float( (s [m - 1]+s [m]) /2 --> returns 4.0

The median is the average of the middle two terms in an even length list. Your M above is not the median, but one of the middle terms. If the list is sorted, then `S[M]` should be 5, and S[M - 1] will be 4.

In Python 2 we would need to compute their sum and convert to a float, then divide by 2. That will give us 4.5 as the median.

In Python 3 the division will give us a float so we don’t need to convert the sum.

Aside

Be mindful of brackets.

Above there are two opening parens, and only one closing paren.

I know M isn’t literally the median here. I’m just using the variables from your previous comment. The median index for a list of 4 numbers would be 1.5 but that doesn’t exist.

And the parenthesis is just a typo in the comment here. Its correct in my code.
Either as a float or not, I’m getting 4 or 4.0 from the return.
I wish Python 3 wasn’t Pro only. Python 2 is weird.

No, it is not the median. It is the index.

``````a = [4, 4, 5, 5]
n = len(a)
m = n // 2
print (m)      # 2
print (a[m])   # 5
print (float(a[m - 1] + a[m]) / 2    # 4.5  =>  median``````

I know. I just said that. That’s not my issue though.
All the variables print correct.
I’m getting 5 and 4 for s[m] and s[m-1].

But with float((s[m] + s[m-1])/2) I get 4.0 Since you’re using Python 2, you have to do it this way it seems:

``````(float(s[m - 1]) + float(s[m])) /2
``````

Hope this helps!

Consider,

``````>>> a = [4, 4, 5, 5]
>>> n = len(a)
>>> m = n // 2
>>> print float(a[m - 1] + a[m]) / 2
4.5
>>>
``````

That’s in Python 2

Your code has the entire expression cast as float. Move the closing bracket to the numerator and leave the `/ 2` outside of it.

I stand corrected. I tried running the code, and would have sworn that I tried:

``````return float(a[m - 1] + a[m]) / 2
``````

and got `4`, but apparently not since it works.

1 Like

def median(lest):
new_lest = lest.sort()
x = len(lest)
if x % 2 == 0:
a = new_lest[x/2]
b = new_lest[x/2 -1]
med = (a + b)/2
else:
med = new_lest[x/2]
return med
why this returns none

Without a block structure to view, we can only assume there is a missing return state, so Python returns None.

1 Like

As a general rule: If one path can lead to return, then every path should lead to return. Your else path leads to return; what about the preceeding if ?

As suggested by @mtf, this would probably be obvious if you were to post your function in Python, a language for which indentations are an essential part. This can be done by using the </> icon in the menu bar of the box you are typing in.

1 Like
``````def median(lest):
new_lest = lest.sort()
x = len(lest)
if x % 2 == 0:
a = new_lest[x/2]
b = new_lest[x/2 -1]
med = (a + b)/2
else:
med = new_lest[x/2]
return med
``````

sorry, didn’t know how to indent in this