This is very similar to Python: split a list based on a condition? and also https://nedbatchelder.com/blog/201306/filter_a_list_into_two_parts.html but instead of partitioning the individual elements into two lists based on a predicate, I want to divide the list into two parts at the first element that fails the predicate.
>>> divide_list(lambda x: x < 7, list(range(10)))
([0, 1, 2, 3, 4, 5, 6], [7, 8, 9])
>>> divide_list(lambda x: x < 7, [1, 3, 5, 7, 9, 5])
([1, 3, 5], [7, 9, 5])
>>> divide_list(lambda x: x < 7, [7, 9, 5])
([], [7, 9, 5])
>>> divide_list(lambda x: x < 7, [1, 3, 5])
([1, 3, 5], [])
>>> divide_list(lambda x: x['a'], [{'a': True, 'b': 1}, {'a': True}, {'a': False}])
([{'a': True, 'b': 1}, {'a': True}], [{'a': False}])
Things to note:
- the input list may not be sorted
- the input list may contain duplicate elements
- ideally we don't want to evaluate the condition multiple times (for each element, if the value is duplicated then that's ok)
- ideally it would accept an iterator as input (i.e. can only do a single pass over the input data)
- returning iterators is acceptable