 # FAQ: Learn Python - Practice Makes Perfect - median

I was able to pass the problem with the following code:

def median(list):

new_list = sorted(list)

if len(new_list) % 2 != 0:

``````median = new_list[len(new_list)/2]

return median
``````

else:

``````index_1 = len(new_list)/2

median_1 = new_list[index_1]

index_2 = index_1 - 1

median_2 =  new_list[index_2]

median = (median_1 + median_2) / 2.

return median
``````

However, I do not understand why my original code was not working:
def median(list):

new_list = sorted(list)

if len(new_list) % 2 != 0:

``````median = new_list[len(new_list)/2]

return median
``````

else:

``````index_1 = new_list[len(new_list)/2]

index_2 = new_list[len(((new_list)/2)-1)]

median = (index_1 + index_2) / 2.

return median
``````

I have the following error for the index_2 line:
TypeError: unsupported operand type(s) for /: ‘list’ and ‘int’

Could something explain me why Python cannot run this/this error ? I don’t see why it considers the len part as a list (I might be wrong on this). To me, the functioning code is similar.

Thank you

Firstly, I’m going to assume you’re using Python 2 and not Python 3, since using `/` can have different results and prevent your code from working properly.

The error specifies the type of problem, namely that you can’t divide a list. If you take a portion of this line:

``````(new_list)/2
``````

you can see that you’re trying to divide a list by 2. This is not permitted. In addition, there are several other aspects of `len(((new_list)/2)-1)` that don’t work out. Try tackling this part again; maybe writing out your thought process as you work through it will help. If you have any more questions, feel free to post them here!

Don’t be afraid to start over. The hints you get here might be helpful, but not as helpful as just clearing the slate and giving it another go. Why fester over a failed bit of code. Toss it, and start over. No real pain in that, and probably less than wrestling with that first attempt. Heave ho, and away we go.

2 Likes

Many thanks for the reply victoria_dr!

I didn’t notice that by adding multiple brackets I changed len(new_list) into a list. The error makes sense now.