List Code Challenges-Create a function called middle_element that has one parameter named lst

Can someone please explain how line of code in bold is working?
#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] #HOW DOES THIS LINE OF CODE WORK?

return sum / 2

else:

return lst[int(len(lst)/2)] #HOW DOES THIS LINE OF CODE WORK?

#Uncomment the line below when your function is done

print(middle_element([5, 2, -10, -4, 4, 5]))

Ty :grinning:

This snippet is basically performing floor division int(len(lst)/2).
In python, int() rounds down to the next available integer (4.4 becomes 4, 4.99999 becomes 4 also).

So let’s think sum = lst[A] + lst[A-1]

Given the information I just gave you, what would the two sides be referring to? Does it make a difference if the list length is odd or even?

Play with this in the terminal interactively and you’ll find it makes a lot more sense!

Hello,
Thank you for your reply.
What I am not understanding is the output of -4.
When I review the snippet int(len(lst)/2) I am thinking:
a) length of list divided by 2 = 3.
My confusion is how are we arriving at -4?

You’re arriving at -4 because that is the element at of the list lst at index number 3:

list: [5, 2, -10, -4, 4, 5]
index: 0  1   2    3   4  5
                   ^
the element at index `3` is -4.
1 Like

Try to have a clear picture of what the function is trying to do… it would make sense if it takes the average of the 2 “middle elements” if it’s a list of even-numbered length (and if so, then sum makes perfect sense as a variable name)

A few strategic print statements can clarify what this particular code does (regardless of what the exercise is asking for)

def middle_element(lst):
	if len(lst) % 2 == 0:
		sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1]
		print("First item: {} + second item {}".format(lst[int(len(lst)/2)], lst[int(len(lst)/2) - 1]))
		print("sum {}/ 2= {}".format(sum,(sum/2)))
		return sum / 2
	else:
		return lst[int(len(lst)/2)]

print(middle_element([5, 2, -10, -4, 4, 5]))

Output:
First item: -4 + second item -10
sum -14/ 2= -7.0
-7.0

1 Like

Can you please break down this code.
how is the first part outputting -4?
I understand the list and indices but not how code is arriving at -4.
Thank you

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

You said you understand lists, list slices and indexes. Therefore, you know:

lst = [1, 2, 3, 4, 5]
lst[3] gives 4
lst[1:] gives [2, 3, 4, 5]
lst[len(lst)-1] gives 5
   because lst[5-1] gives lst[4] gives 5

Therefore, when you see lst[int(len(lst)/2)], you know (the list: [5, 2, -10, -4, 4, 5]):
len(lst) = 6.
len(lst)/2 = 6/2 = 3.
int(len(lst)) = int(6/2) = int(3) = 3.
So, now you have lst[int(len(lst)/2)] = lst[3]. Now, lst[3] gives -4:

list:   [5, 2, -10, -4, 4, 5]
         |  |   |    |  |  |
indexes: 0, 1,  2,   3, 4, 5
                     ^
1 Like