Printing the Middle Element of a List

In this article, we will learn how to print the middle element of a list using Python. A common use case for this is to find the middle index in a list if that list happens to be sorted and its elemen …

Updated October 13, 2023

In this article, we will learn how to print the middle element of a list using Python. A common use case for this is to find the middle index in a list if that list happens to be sorted and its elements have equal values (like finding the median).

For printing any middle element of a list, you can simply choose the index as len(list)/2. However, this will work only if the length is an integer. If it’s not, Python rounds down to the nearest integer. So, for lists with uneven lengths, we need to get the middle two elements and return either one depending on whether the list length is odd or even.

Here’s how you can do this:

def print_middle(lst):
    mid = len(lst) // 2
    if len(lst) % 2 == 0:   #even number of elements in the list
        return lst[mid - 1 : mid + 1]
    else:                  #odd number of elements in the list
        return [lst[mid]]

In this function, if you pass a list with an even length, it will return both middle elements. If you pass a list with an odd length, it will return only one middle element. It works with any type of data in the list because Python can automatically convert a single object to a list with a single element when slicing. You can test this function using some examples:

print(print_middle([1,2,3,4])) # [2]
print(print_middle([5,5,5,5])) # [5]
print(print_middle([7,2,9,0,6,1])) # [2, 9]

This function can be very useful in different situations where you need to get the middle element or elements of a list. For instance, if you are calculating some statistics over a list of numbers and you want to know which number is in the middle (or the two that are in the case of an even-lengthed list).

Hey! Do you love Python? Want to learn more about it?
Let's connect on Twitter or LinkedIn. I talk about this stuff all the time!