Optimized method of cutting/slicing sorted lists

Bisect left and right helper function

#!/usr/bin/env python3

import bisect

def get_slice(list_, left, right):
    return list_[
        bisect.bisect_left(list_, left):
        bisect.bisect_left(list_, right)
    ]

assert get_slice([0, 1, 1, 3, 4, 4, 5, 6], 1, 5) == [1, 1, 3, 4, 4]

Tested in Ubuntu 16.04, Python 3.5.2.


You can use the bisect module to perform a sorted search:

>>> import bisect
>>> a[bisect.bisect_left(a, 6):]
[7, 9]

If you just want to filter the list for all elements that fulfil a certain criterion, then the most straightforward way is to use the built-in filter function.

Here is an example:

a_list = [10,2,3,8,1,9]

# filter all elements smaller than 6:
filtered_list = filter(lambda x: x<6, a_list)

the filtered_list will contain:

 [2, 3, 1]

Note: This method does not rely on the ordering of the list, so for very large lists it might be that a method optimised for ordered searching (as bisect) performs better in terms of speed.


bisect.bisect_left is what you are looking for, I guess.

Tags:

Python

List

Find