Why are the preceding **lst** required?


Middle Item

I have 2 questions with this solution;

sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1]

I get that these sections of code are indices for the two middle integers in the list. And that they are being added together so we can return the average in the next line. But why are the preceding lst required?

if len(lst) % 2 == 0:

Can anyone explain what the “%” function actually does? How it works etc

FAQ: Code Challenge: Lists - Middle Item
FAQ: Code Challenge: Lists - Middle Item

That is called a parity check, or a check for evenness. The mdoulo operator, % indicates remainder division. If a number divided by 2 has no remainder, then the number is even.

This relates to a statistics concept, median which is the middle of a sorted sample list. If the list is even-length, then we need to draw out the middle two indexes; if odd we use only the single middle index.

It’s not the integers that we are drawing out, but the indexes for those elements. Once we have the two middle indexes we can poll the values, add them and take their average as the median.

Note that in this exercise we are not sorting the list, only finding the physical middle of the list, not the median.

We can see in the earlier example that rather than repeat len(lst) / 2 or 1en(lst) we cache those values in n and m.

n = len(lst)    # n will be an integer
m = n // 2      # because we use integer (floor) division, m is an integer

Now with this information all we need to determine is the parity of the length so we know whether to return one term, or the average of two.

if n % 2:
    return lst(m)
    return float(lst[m - 1] + lst[m]) / 2


ty very much. I couldn’t figure out how to get the function to determine if the list was odd or even the explanation of the mdoulo operator helps tremendously.