0

Excuse my ignorance as I am still freshly new to python programming.

My issue is trying to iterate through a list and trying to find the median of each value in the list. For now, I think I am getting the right idea as I am looping through my data list and print out each output. I am stuck on trying to implement the statistics module to work with the median() method to get an output. Here is my code...

import  statistics

number_data = [2, 1, 5, 7, 2, 0, 5]

def median_number(num):
    for i in num:
        print('Median:', i)


median_number(number_data)
Oscar Pacheco
  • 47
  • 1
  • 1
  • 7
  • See if this helps, https://stackoverflow.com/a/9039992/4985099 – sushanth Jun 14 '20 at 07:42
  • Does this answer your question? [Finding the average of a list](https://stackoverflow.com/questions/9039961/finding-the-average-of-a-list) – George Udosen Jun 14 '20 at 07:43
  • 6
    The median is a property of a list, not of a single value. It represents the middle value in a list. Order the list and take the middle value: 0, 1, 2, 2, 5, 5, 7. Hence the middle value would be 2nd 2. So the median would be 2. – DJanssens Jun 14 '20 at 07:44
  • Perfect! That makes sense! @DJanssens thank you for that comment – Oscar Pacheco Jun 14 '20 at 07:50

2 Answers2

0

Median is a property of a list - aka the middle value when the list is sorted.

>>from statistics import median
>>print(median([2, 1, 5, 7, 2, 0, 5]))
2
Kaushik J
  • 962
  • 7
  • 17
0

You find a median value of a set of values, not one number. To implement it using the statistics module, please do:

import  statistics
number_data = [2, 1, 5, 7, 2, 0, 5]
print(statistics.median(number_data))

You could also use numpy https://numpy.org/doc/stable/reference/generated/numpy.median.html

Ports
  • 419
  • 2
  • 7