Find middle of a list

Question:

How would I find the exact middle of a python list?

aList = [1,2,3,4,5]
middle = findMiddle(aList)
print middle

This is just an example of a function that would be able to find the middle of any list, is this something you can do using list comprehension?

Edit: This is different than taking out the middle point because I would like to just print out the middle value, if the list is odd I would like to return both the middle values like the accepted answer. Not getting the median like the other question has asked and getting the average of the two values.

Asked By: Alastair

||

Answers:

Take the length of the list, cut that in half and access whatever the list at that index point.

Answered By: Martin Lear

Why would you use a list comprehension? A list comprehension only knows about any one member of a list at a time, so that would be an odd approach. Instead:

def findMiddle(input_list):
    middle = float(len(input_list))/2
    if middle % 2 != 0:
        return input_list[int(middle - .5)]
    else:
        return (input_list[int(middle)], input_list[int(middle-1)])

This one should return the middle item in the list if it’s an odd number list, or a tuple containing the middle two items if it’s an even numbered list.

Edit:

Thinking some more about how one could do this with a list comprehension, just for fun. Came up with this:

[lis[i] for i in 
    range((len(lis)/2) - (1 if float(len(lis)) % 2 == 0 else 0), len(lis)/2+1)]

read as:

“Return an array containing the ith digit(s) of array lis, where i is/are the members of a range, which starts at the length of lis, divided by 2, from which we then subtract either 1 if the length of the list is even, or 0 if it is odd, and which ends at the length of lis, divided by 2, to which we add 1.”

The start/end of range correspond to the index(es) we want to extract from lis, keeping in mind which arguments are inclusive/exclusive from the range() function in python.

If you know it’s going to be an odd length list every time, you can tack on a [0] to the end there to get the actual single value (instead of an array containing a single value), but if it can or will be an even length list, and you want to return an array containing the two middle values OR an array of the single value, leave as is. 🙂

Answered By: Kyle Baker

Something like this would do:

aList = [1,2,3,4,5]
#minus 1 because the first element is index 0
middleIndex = (len(aList) - 1)/2
print middleIndex
print aList[middleIndex]
Answered By: heinst

Are you expecting something like

def findMiddle(list):
  l = len(list)
  if l/2:
    return (list[l/2-1]+list[l/2])/2.0
  else:
    return list[(l/2-1)/2]
Answered By: Yiwen Shi
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.