S1Q1 · Extract Middle Elements from a List¶
⚡ Quick Reference
Function: extract_middle_elements(lst: list) -> list
Core idea: find the midpoint, return one or two elements depending on parity.
def extract_middle_elements(lst: list):
mid = len(lst) // 2
if len(lst) % 2 == 1:
return [lst[mid]]
else:
return [lst[mid - 1], lst[mid]]
Key rules:
- Odd length → one middle element at index n // 2
- Even length → two middle elements at indices n//2 - 1 and n//2
- Always returns a list
Problem Statement¶
Problem
Write a function extract_middle_elements(lst) that returns a list containing the middle element (odd length) or the two middle elements (even length).
Examples:
[7, 8, 9, 10, 11, 12, 13]
[10]
[3, 6, 9, 12, 15, 18]
[9, 12]
Tracing both examples¶
Example 1: [7, 8, 9, 10, 11, 12, 13] - length 7 (odd)
Example 2: [3, 6, 9, 12, 15, 18] - length 6 (even)
Solution approaches¶
Key takeaways¶
mid = n // 2 - works for both parities
For odd length, n//2 is the exact centre. For even length, n//2 is the right-of-centre element, and n//2 - 1 is the left-of-centre. One formula covers both cases.
lst[start:mid+1] - slice returns a list
Slicing a list always returns a list, so lst[start:mid+1] avoids wrapping in []. For odd length start==mid, giving a one-element slice; for even start==mid-1, giving two elements.
Always return a list, not a single value
Even the odd-length case returns [lst[mid]] - a list containing one element, not the bare element. The function always returns a list for consistency.