Python Program to Find the Median of a List
In this tutorial, we will discuss a Python program to find the median of a list.
Before going to the program first, let us understand what is Median.
Median:
- The median is the middle value of the list when the list is sorted.
Related: Python Program to Find the Mode of a List
Program code to find the median of a list in Python
# Find the Median of a List in Python def find_median(lst): lst.sort() n = len(lst) mid = n // 2 if n % 2 == 0: return (lst[mid - 1] + lst[mid]) / 2 else: return lst[mid] input_list = [7, 1, 3, 4, 6, 5, 2] median = find_median(input_list) print("Median of the list:", median)
Explanation
- Function Definition: The
find_median
function takes a list as input, sorts it, and returns the median of the list. - Main Program: The program defines a list and finds the median using the
find_median
function. It then prints the result.
Output
- When you run the above program, it will find the median of the list and print the result.
Conclusion
- In this tutorial, we learned a Python program for finding the median of a list.
- Understanding this concept is essential for data analysis and enhancing your programming skills.