Alastair Beaumont Alastair Beaumont - 1 year ago 57
Python Question

Find middle of a list

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

Answer Source

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 difficult. Instead:

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

This is very close to what you want. Tweak a little for handling even/odd lists as desired.

edit: did some example tweaking. 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.