Skip to content

S1Q1 · Extract Border Elements from a List

⚡ Quick Reference

Function: extract_border_elements(arr: list) -> list

Core idea: handle three cases - empty, single element, multiple elements.

def extract_border_elements(arr: list) -> list:
    if len(arr) == 0:
        return []
    if len(arr) == 1:
        return [arr[0]]
    return [arr[0], arr[-1]]

Key rules: - Empty list → [] - Single element → [arr[0]] - Two or more elements → [arr[0], arr[-1]]


Problem Statement

Problem

Write a function extract_border_elements(arr) that returns a list with the first and last elements of the input list, handling edge cases for empty and single-element lists.

Examples:

Input
[1, 2, 3, 4]
Output
[1, 4]
Input
[5]
Output
[5]
Input
[]
Output
[]
Input
[7, 8, 9, 10, 11]
Output
[7, 11]

Tracing all examples

Input Length Case Output
[1, 2, 3, 4] 4 > 1 [arr[0], arr[-1]] = [1, 4]
[5] 1 == 1 [arr[0]] = [5]
[] 0 == 0 []
[7, 8, 9, 10, 11] 5 > 1 [7, 11]

Solution approaches

def extract_border_elements(arr: list) -> list:
    if len(arr) == 0:
        return []
    if len(arr) == 1:
        return [arr[0]]
    return [arr[0], arr[-1]]
def extract_border_elements(arr: list) -> list:
    if not arr:
        return []
    return list({0: arr[0], -1: arr[-1]}.values()) if len(arr) > 1 else [arr[0]]
def extract_border_elements(arr: list) -> list:
    if not arr:
        return []
    if len(arr) == 1:
        return arr[:]
    return [arr[0], arr[-1]]

arr[:] returns a shallow copy of the list - works cleanly for the single-element case.

extract_border_elements = lambda arr: (
    [] if not arr else
    [arr[0]] if len(arr) == 1 else
    [arr[0], arr[-1]]
)

Key takeaways

01

Handle edge cases first

Check empty and single-element cases before the general case. This avoids index errors and keeps the logic flat - no nested conditions needed.

02

arr[-1] for the last element

Negative indexing always gives the last element regardless of list length. arr[-1] is cleaner than arr[len(arr)-1] and works for any non-empty list.

03

if not arr - Pythonic empty check

Empty lists are falsy in Python. if not arr is the idiomatic way to check for an empty list - equivalent to if len(arr) == 0 but shorter.