Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

How do you find the median of a list in Python? The list can be of any size and the numbers are not guaranteed to be in any particular order.

If the list contains an even number of elements, the function should return the average of the middle two.

Here are some examples (sorted for display purposes):

median([1]) == 1 

median([1, 1]) == 1 

median([1, 1, 2, 4]) == 1.5 

median([0, 2, 5, 6, 8, 9, 9]) == 6 

median([0, 0, 0, 0, 4, 4, 6, 8]) == 2

2 Answers

0 votes
by (106k points)

To find median of the list in Python you can use the below-mentioned code:-

def median(lst): 

quotient, remainder = divmod(len(lst), 2) 

if remainder: 

return sorted(lst)[quotient] 

return sum(sorted(lst)[quotient - 1:quotient + 1]) / 2.

0 votes
by (20.3k points)

Try using this:

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]

sum(l) / float(len(l))

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...