# Middle_element(lst) in Python Lists

#1

Dear all,

please excuse me, but I didn’t understand a thing in this one!

`middle_element(lst)`

Instructions

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.

#2

The middle element of an odd length list will be,

``````lst[int(len(lst) / 2)]
``````

The middle two elements of an even length list will be,

``````lst[int(len(lst) / 2) - 1] and lst[int(len(lst) / 2)]
``````

Clearly there is repetition here so we can cache the general expression.

``````n = int(len(lst) / 2)
``````

so that odd length is,

``````lst[n]
``````

and even length are,

``lst[n - 1] and lst[n]``

#3

If I gave you a piece of paper with numbers, could you carry that out?

If so, what exactly did you not understand about that, have you thought through what you’re missing? Maybe start with that, because it gives you something to figure out and then keep going.

#4

Thank you both. Yes I have thought and it seems that this whole “Code Challenge: Lists” is one of my worst, if not the worst. I seem to not grasp at all the (lst) thing. I am however totally new to coding and just starting out.

Also I am very confused as to where I only use lst, e.g. lst1, lst2 in the solution and where I use len, e.g.: len(lst1), len(lst2).

#5

`len()` is global function that we use anytime we want to know the element or item count of an object.

``````>>> a = [1,1,2,3,5,8,13]            # list class
>>> len(a)
7
>>> b = {'a': 1, 'b': 2, 'c': 3}    # dict class
>>> len(b)
3
>>> c = {8,2,6,9,3,5}               # set class
>>> len(c)
6
>>> d = (a,b,c)                     # tuple class
>>> len(d)
3
>>> e = "string"                    # str class
>>> len(e)
6
``````

Since we should avoid using class names as variables, `lst` is commonly used to represent a list object. Variable names are completely arbitrary and often derive their name for the objects they contain.

``````fruits = ['apple', 'banana', 'cherry', 'date']

dogs = ['Labrador', 'German Shepherd', 'Collie', 'Great Dane']
``````

and so on.

#6

Hello! I am having trouble with the same problem as the initial poster. Something I am puzzled by:

``````a = [1,5,4]
len(a)
3
``````

This makes sense to me. However:

``````a = [1,5,4]
len(a)
3
a [int(len(a)/2)]      #???
5
``````

Why would that final line yield 5 in this circumstance? The total length of the list is 3, so len(a) / 2 = 1.5, which I would have thought would produce an error when posed as an index for the list.
Thank you for any advice.

#7
``````    int(len(a) / 2)  =>  1

a[1]  =>  5
``````

Aside

Do not leave whitespace between the identifier and the subscript. Keep them tight together.

#8

Correct. List indexes are discrete, there’s nothing between them so 1.5 as an index doesn’t make sense.
When you do integer divison, you get an integer.
You should also not convert to int after doing floating point division, that’s an incredibly strange thing to do because floating point operations are far more complicated and they aren’t exact - stick with integer operations. In this case, assuming python2 is used, it is integer division, and then it’s converted from int to int which also doesn’t make sense.

#9

Thank you for your advice. Interestingly, the hint for this exercise states:

"The index of the middle element can be found by using `len(lst)/2` . However, division results in a float, and indices must be integers. You can cast that number to be an integer using `int(len(lst)/2)` .

For lists with an even number of indices, you will want the element at the index found above and also the element at index `int(len(lst)/2) - 1`"

Does it seem to you that the int() command is unnecessary in this case?

#10

I appreciate your advice. However, I am still unclear:

Does the len() command yield a value of 2 in this circumstance because Python is zero-indexed? When I print the length of this list, it gives a value of 3. Wouldn’t 3 divided by 2 yield 1.5 instead of 1?

#11

In Python 2 it will yield 1 since version 2 uses integer division. In Python 3 we could write,

``````len(a) // 2
``````

which would also be 1. Indices cannot be floats, and iterables are zero-indexed, hence the middle element of a list with length 3 will be at index 1.

#12

zero-indexing doesn’t affect the size of a container. An empty container needs to have a size of 0, you can’t get away from that.

Integer division can’t produce 1.5 because that’s not an integer. 3 divided by 2 is 1 when you only use integers, the remainder is discarded.

Casting isn’t something done in python. It’s conversion. And regardless of which python version is used it is wrong to convert at that time for the reasons i mentioned in last post. When you’re dealing with indexes it should all be integer math, if there’s a float involved anywhere it’s probably wrong and the fix isn’t to convert, it’s to not have it in the first place

#13

Bear in mnd that this is from the instructions, and not contrived by the OP. We get caught in the trap of trying to correct a learner’s code when they are just following instructions. Theory injection usually comes with glossed over eyes or an endless stream of questions tha tonly derails the learner’s progress in the track. Once they get through all the lessons, theory has a better chance of raising some interest and receptivity.

#14

Thank you both for your help. I see the value in keeping strictly to integers when dealing with indices - I am not sure why the hint mentions the int() command if it is unnecessary. Regardless, I now understand integer division, which is useful. I will keep chipping away.

#15

What is necessary is learning all the functions in the Standard Library, of which `int()` is one. It’s too early to argue against its use. First we need to learn how to use it, then learn alternate approaches. In time we learn how to control our data types and ways and means to limit resource usuage and optimize our code. That time is not now, however. Keep on building your toolbox and soak up all the beginner stuff you can. There is a lot of detail that can wait until later, just remember to keep circling back and covering old ground again and again.

#16

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.