Menu

gitpiper

median python Code Snippet in 2023

mathbeginner

Last Updated: 28 May 2023

Finds the median of a list of numbers.

  • Sort the numbers of the list using list.sort().
  • Find the median, which is either the middle element of the list if the list length is odd or the average of the two middle elements if the list length is even.
  • statistics.median() provides similar functionality to this snippet.
def median(list): list.sort() list_length = len(list) if list_length % 2 == 0: return (list[int(list_length / 2) - 1] + list[int(list_length / 2)]) / 2 return float(list[int(list_length / 2)])
median([1, 2, 3]) # 2.0 median([1, 2, 3, 4]) # 2.5

python snippet similar to median For You in May 2023

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2023 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️