Skip to main content

How to find the median of elements in a list in Python

How to find the median of elements in a list in Python.

Here's a step-by-step tutorial on how to find the median of elements in a list using Python:

Step 1: Start by creating a list of elements for which you want to find the median. For example, let's consider the list [5, 7, 2, 9, 1].

Step 2: Sort the list in ascending order. This is necessary to find the middle element(s) in the list. You can use the built-in sorted() function to sort the list. For example:

elements = [5, 7, 2, 9, 1]
sorted_elements = sorted(elements)

After sorting, the sorted_elements list will be [1, 2, 5, 7, 9].

Step 3: Check the length of the sorted list using the len() function. If the length is odd, the median will be the middle element. If the length is even, the median will be the average of the two middle elements.

Step 4: Calculate the median based on the length of the sorted list. Here are two examples:

  • If the length is odd:
median = sorted_elements[len(sorted_elements) // 2]
  • If the length is even:
middle1 = sorted_elements[(len(sorted_elements) // 2) - 1]
middle2 = sorted_elements[len(sorted_elements) // 2]
median = (middle1 + middle2) / 2

In the first example, we use integer division (//) to make sure we get the index of the middle element. In the second example, we calculate the average of the two middle elements.

Step 5: Finally, you can print or use the calculated median value as needed. For example:

print("The median is:", median)

Here's the complete code:

elements = [5, 7, 2, 9, 1]
sorted_elements = sorted(elements)

if len(sorted_elements) % 2 == 1:
median = sorted_elements[len(sorted_elements) // 2]
else:
middle1 = sorted_elements[(len(sorted_elements) // 2) - 1]
middle2 = sorted_elements[len(sorted_elements) // 2]
median = (middle1 + middle2) / 2

print("The median is:", median)

This code will output 5, as it is the median of the given list [5, 7, 2, 9, 1].