How does `len()` of a list work?

Middle Item

What I do not understand about this exercise is why the ‘list’ command, which is supposed to give you the length of the total list, gives you a number that is actually in the list.

Using my logic, this:

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

should return: length of the list, 6, devided by 2 = 3 + lentgh of the list, again, 6, divided by 2, = 3, then - 1 = 5
instead it takes the middle 2 numbers, is that because of int? I thought that was just to indicate a number.

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

so len(lst) is returning 6. 6 / 2 is an index of 3.
so that’s the 4th element, ie, -4
so then it’s doing the same thing, 6/2 = 3. now it’s subtracting 1, which gives us a index of 2.
which means the 3rd element -10

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

4 Likes

When something is getting complicated, it needs to be simplified to remove repetition.

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

Now we can add the two with ease…

sum = lst[m - 1] + lst[m]

The relates to a statistics concept, median, which will no doubt come up at some point. However, in this exercise we are not sorting the list, only finding the middle one or two elements, depending on parity.

9 Likes

Thanks, I understand now!

1 Like

Thank you for that simplified explanation. I used a different code that CA solution, but got a correct answer by correcting syntax. Using the word "median in the question would have helped me visualize the answer.
Anyway, thanks for breaking it down.:+1:

Thanks for breaking it down mtf!

1 Like

Thank you for the explanation: I understand the code in case the number of elements in the list is even.

I dont understand the code when the number of elements in the list is odd. The solution given by codeacademy for an odd number of elements is:

else:
return lst[int(len(lst)/2)]

Let’s say there are 7 elements in this list, then wouldn’t that yield 7/2 = 3.5?

1 Like

When seeking the middle element in a list, we must first arrive at an integer that can be used as an index.

n = len(a_list)
m = int(n / 2)

If the length is 7, the middle element will be at index 3.

0 1 2 3 4 5 6
      ^
1 Like

thank you for your quick response - I appreciate it.

If I apply the formulas you shared for for the below list, I still get stuck.

list [5, 2, -10, -4, 4, 5, 7]

n = len(a_list)

for the above list, n =7

m = int(n / 2)

m= int(7/2)
=3.5

Kindly let me know if I’m doing something wrong here.

1 Like

It would need to be an assignment.

a_list = [5, 2, -10, -4, 4, 5, 7]

For the sake of protecting your code environment, avoid the use of reserved keywords. list is the name of the built in list constructor, list(). My variable above reads, ‘a list’.

n = len(a_list)    # 7
m = int(n / 2)     # 3

Note that we use the int constructor to ensure the result can be used as an index. Floats cannot be used as indices.

Now we can retrieve the middle value of the list,

a_list[m]           # -4

Something we use above is, floor division using the special operator, //. This will give us an integer result if both values in the division are integers. If one or both are floats, it will be a decimal (float) with .0 tacked on.

Since we are dividing two integers, we could write,

m = n // 2
3 Likes

Got it. Very helpful. Thank you!

1 Like

I have a question about the same lesson. I understand this one, but what happen when you change the -1? This one for example: lst[int(len(lst)/2)-2 ] I understand about the -1, but i can’t get my head around what happens when you change that number.

I started with python a week ago, so maybe it is simple but am just a beginner :slight_smile:

Draw a list on paper and choose an index. Point at that location in the list.
Then pick an index that is 1 smaller. Point at it. What was the difference?

There wouldn’t be anything other than that happening, would there?

Thanks for responding. But if i run this in python il get a answer( a int) that isn’t in the list. Thats the strange part.

Then it doesn’t come from the code that looks up a value from your list, so this operation would not explain it.
But if you look at the code that does the printing and then follow that value backwards through your code then you’ll find the source.

def middle_element(lst):
if len(lst) % 2 == 0:
sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 4]
return sum / 2
else:
return lst[int(len(lst)/2)]

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

OUTPUT: 0.5 at the terminal

So where does 0.5 come from? It is not on the list, and it comes from this code.

If you know what each thing there does then you can run it in your head. The data input is small enough for it. If not, then you can find out more about whatever you’re missing.

You can change it too, see what happens.
One such change is to print things out.

Or like I suggested last post, work your way backwards from the print.

I already understand it thanks for your help!

My mistake :the math is done with the numbers at the index and not at the index itself.

Im doing the following code:

#Write your function here
def middle_element(lst):
  if len(lst)%2 != 0:
    middle = int(len(lst)/2)
    print(lst[middle])
    return lst[middle]
  else:
    middle = int(len(lst)/2)
    print(lst[middle])
    middle2 = int(len(lst)/2) - 1
    print(lst[middle2])
    return lst[middle2] + lst[middle]
  
#Uncomment the line below when your function is done
print(middle_element([5, 2, -10, -4, 4, 5]))

I’m getting the correct middle ones but the exercise told me that I should receive -7

any advice?

I’m using the print statemens in order to see what results im getting, they are just informatinal