Python
- key differences between List and Arrays
- Python collections ChainMap
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python collections
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions in Python
- key differences between List and Arrays
- Program: Calculate Pi in Python
- String Formatting in Python
- Python counters
- python tuples
- Python deque
- Python dictionary
- Python Lists
- python namedtuple
This article provides a Python solution to find the middle element in a given integer array. The algorithm efficiently calculates the middle element for arrays with odd lengths or returns the average of the two middle elements for arrays with even lengths. By implementing this Python code, you can easily determine the middle element of any integer array.
def middle_element(lst):
lst_len = int(len(lst))
if len(lst) % 2 != 0:
return lst[lst_len // 2]
else:
return ( lst[int(lst_len/2)-1] +
lst[int(lst_len/2)] ) / 2
Example usage:
array = [1, 9, 3, 4, 5,6,7,8,10]
middle_element = middle_element(array)
print("Middle Element:", middle_element)
#Output
Middle Element: 5