Advance Python code challenges: Middle item

hi, everyone. I need you to help here. I got stuck in following,

below a solution to an advanced python code challenges to find the Middle item

                                                                Find Middle item

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.

#Write your function here
def middle_element(lst):
  if len(lst) % 2 == 0:
    **sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1]**
    return sum / 2
  else:
    return lst[int(len(lst)/2)]

#Uncomment the line below when your function is done
print(middle_element([5, 2, -10, -4, 4, 5]))

I could not understand this line:

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

plz explain to me :kissing_smiling_eyes:

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

sum = set the variable sum to the value on the right of the equals sign.
lst[] gets an element or slice from the list lst.
int() casts the given argument to a type int (integer).
len(lst) returns the length of the list lst.
/2 divides by two.
Therefore the expression lst[int(len(lst)/2)] find the item of the list lst at the position of the length of the list (len(lst)) divided by 2. In other words, one of the middle terms.

What do you mean "one of the middle terms"?

A list with an even number of elements has two middle terms:

[1, 2, 3, 4]
    ^  ^

See, elements 2 and 3 both have the same number of elements on the side closest to the end of the list?

Then, the second half of the expression (lst[int(len(lst)/2) - 1]) does everything the above does, except finds the lower middle term:

lst = [1, 2, 3, 4]

The first half (lst[int(len(lst)/2)] find the element at lst[int(len(lst)/2)] = lst[int(4/2)] = lst[2], which is a list index for the element with an index of 2: the number 3. The second half of the expression (lst[int(len(lst)/2) - 1]) find the element directly before 3: the number 2.

After getting the two middle terms, this adds them together.
I hope this helps!

2 Likes