Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Sort items with a key that handles missing values

Sort iterables with keys that may be missing or None, keeping missing items at the end reliably.

Python practice26 minFunctions as Objects (Lambda, Map/Filter)AdvancedLast updated March 20, 2026

Problem statement

When sorting a collection, the key function you use might return None or fail to find a value for some items. A robust sort should place items with missing or None keys at the end (after all present keys), regardless of ascending/descending order. Write sort_with_missing(items, key_func, missing_value=None, reverse=False) that: - Accepts items: an iterable (e.g., list) of elements to sort. - Accepts key_func: callable that returns a key for each item or None to indicate missing. - Accepts missing_value: optional placeholder (not required for the algorithm but kept for signature compatibility). - Accepts reverse: if True, sort present items in descending order, but still place missing items at the end. - Returns a new list with present-key items sorted and missing-key items appended in their original relative order.

Task

Implement sort_with_missing(items, key_func, missing_value=None, reverse=False) that sorts while ensuring missing keys are placed at the end.

Examples

Sort dicts by age, place missing ages last

Input

sort_with_missing([{'name':'a','age':30},{'name':'b','age':None},{'name':'c','age':25}], lambda d: d.get('age'))

Output

[{'name': 'c', 'age': 25}, {'name': 'a', 'age': 30}, {'name': 'b', 'age': None}]

Items with age None are placed at the end; remaining items are sorted by age ascending.

Input format

Three positional arguments: items (iterable), key_func (callable), optional keyword reverse (bool).

Output format

A Python list with sorted items; missing-key items appended at the end.

Constraints

- The original relative order of items with missing keys should be preserved. - Do not modify the original items collection in-place. - Assume key values returned for present items are mutually comparable.

Samples

Sample 1

Input

sort_with_missing([{'id':1,'value':'b'},{'id':2},{'id':3,'value':'a'}], lambda d: d.get('value'))

Output

[{'id': 3, 'value': 'a'}, {'id': 1, 'value': 'b'}, {'id': 2}]

'value' missing in second item so it's placed at the end.