Skip to content

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:

Input
[7, 8, 9, 10, 11, 12, 13]
Output
[10]
Input
[3, 6, 9, 12, 15, 18]
Output
[9, 12]

Tracing both examples

Example 1: [7, 8, 9, 10, 11, 12, 13] - length 7 (odd)

mid = 7 // 2 = 3
lst[3] = 10
→ [10] ✓

Example 2: [3, 6, 9, 12, 15, 18] - length 6 (even)

mid = 6 // 2 = 3
lst[mid-1] = lst[2] = 9
lst[mid]   = lst[3] = 12
→ [9, 12] ✓


Solution approaches

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]]
def extract_middle_elements(lst: list):
    n   = len(lst)
    mid = n // 2
    if n % 2 == 1:         # odd length
        return [lst[mid]]
    else:                   # even length
        return [lst[mid - 1], lst[mid]]
def extract_middle_elements(lst: list):
    n     = len(lst)
    mid   = n // 2
    start = mid if n % 2 == 1 else mid - 1
    return lst[start : mid + 1]

For odd length: lst[mid:mid+1] → one element. For even length: lst[mid-1:mid+1] → two elements. Slice returns a list directly - no explicit list construction needed.

extract_middle_elements = lambda lst: (
    [lst[len(lst)//2]] if len(lst) % 2 == 1
    else [lst[len(lst)//2 - 1], lst[len(lst)//2]]
)

Key takeaways

01

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.

02

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.

03

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.