Python: Code Challenges: Lists (Advanced) - "Middle Item"

The problem: ‘Create a function called middle_element that has one parameter named lst .
If there are an odd number of elements in lst , the function should return the middle element. If there are an even number of elements, the function should return the average of the middle two elements.’

I was just wondering if someone could help explain how to do this in more simple terms. I have read through the answer but am having trouble grasping the concept and understanding the explanation below…

The solution: ’ We used modulus to determine if the list had an even or odd number of elements. After determining this, for an odd number of elements, we calculate the middle index and return the middle element from the list. For an even number of elements, we calculate the index of the element close to the middle and the other element close to the middle (by subtracting 1 from the middle calculation). We get the values at those indices and calculate the average.

Note that the math to find the middle index is a bit tricky. In some cases, when we divide by 2 , we would get a double. For example, if our list had 3 items in it, then 3/2 would give us 1.5 . The middle index should be 1 , so in order to go from 1.5 to 1 , we cast 1.5 as an int . In total, this is int(len(lst)/2) .’

Whether the list length is odd or even, floor dividing the integer by 2 will give the same integer value.

n = len(lst)
m = n // 2

We only need to do that calculation once, and store the value.

We can go straight to the return if the length is odd.

if n % 2:
    return lst[m]

Now if we reach this point we know the length is even so compute the average and return the float.

return (lst[m] + lst[m - 1]) / 2    # Python 3

return (lst[m] + lst[m - 1]) / 2.    # Python 2
1 Like