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.
The for loop is used to access the values in the list ( l ), and the if condition is used to check if the elements in the given list ( l ) are present in the empty list ( l1 ). If the elements are not present, those values are appended to the list ( l1 ); else, they are printed. Here, the list ( l1 ) has no duplicates.
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]
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 i
th 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. :)
Take the length of the list, cut that in half and access whatever the list at that index point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With