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)])
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.
sorted list is [1, 2, 3, 4, 9, 10, 44] mid value is 4
You might also like :
- Find total number of lowercase characters in a string using Python 3
- Python program to find the circumference of a circle
- Python program to find the sum of all values of a dictionary
- Python program to find the maximum and minimum element in a list
- Python program to find the multiplication of all elements in a list
- Python program to find the square root of a number