Python program to find the middle element of a random number list

Python program to find the middle element of a random number list :

In this python programming tutorial, we will learn how to find out the mid number in a number list. For example, if the list is [1,6,5,4,3], the mid element is 4. Because two numbers 1,3 are less than 4 and two elements 5,6 are greater than 4. Our list will contain an odd number of elements.
To solve this problem, we will first sort the list. Then the middle element will be in the mid position of the list. We can find out the mid position easily by finding out the length of the list. Let me show you with code :

Python program :

#1
my_list = [4,3,2,9,10,44,1]

#2
my_list.sort()

#3
print("sorted list is ",my_list)

#4
print("mid value is ",my_list[int(len(my_list)/2)])

Explanation :

The commented numbers in the above program denote the step numbers below :

1. my_list is the given list, we need to find out the mid element of this list.
2. Using .sort() method, we can sort a list in python. This method doesn’t return any value. It sorts all elements in the list we are calling sort().
3. Print out the sorted list.
4. Print the middle value of the sorted list by accessing the size of the list/2 position. To get the length of a list, we are using len(list) method.

Output :

sorted list is  [1, 2, 3, 4, 9, 10, 44]
mid value is  4

python find mid number
You might also like :

2 Replies to “Python program to find the middle element of a random number list”

  1. list=[1,2,3,4,5,6,7,8,9,10]
    i want to find middle number in a list.Here 10 numbers are there i want output [5,6] like this.Can u please explain it

  2. you can first check the length of the list. If is odd then it will be same as like we have shown in this example. If it is even then you can print the numbers : my_list[len(my_list)/2)] and my_list[len(my_list)/2) – 1]

Leave a Reply