@alicederyn On second thought, although it isnât my personal use case, I imagine that it may still be useful for simplifying other bisect recipes such as find_gt where a default value is returned instead of raising an exception:
def find_gt(a, x):
'Find leftmost value greater than x'
i = bisect_right(a, x)
if i != len(a):
return a[i]
return None
I still struggle to imagine a real-world use case for having a default value for missing items in a list slice. Do share some if you can think of any.
Note that your example of a rolling window can also be done with a modified sliding_window recipe from the itertools doc, although I canât think of a good use for the fill values:
def sliding_window(iterable, n, default):
"Collect data into overlapping fixed-length chunks or blocks."
# sliding_window('ABCDEFG', 4, 'X') â ABCD BCDE CDEF DEFG EFGX FGXX GXXX
iterator = iter(iterable)
window = deque(islice(iterator, n - 1), maxlen=n)
for x in chain(iterator, repeat(default, n - 1)):
window.append(x)
yield tuple(window)
I didnât attribute any substantial weight to it, It is more of a fun quick possibility.
I thought if I share it maybe someone will come up with actually useful applications.
Also, its performance in practice is very similar to the recipe you provided. So itâs just a possibility without fancy recipes (or dependencies) for certain cases.
I donât think so. What I had in mind is:
Script
class get:
def __init__(self, idx, default=None):
self.idx = idx
self.default = default
def __rmatmul__(self, lst):
idx, default = self.idx, self.default
if isinstance(idx, slice):
start = 0 if idx.start is None else idx.start
stop = len(lst) if idx.stop is None else idx.stop
step = 1 if idx.step is None else idx.step
result = list()
for i in range(start, stop, step):
try:
item = lst[i]
except (IndexError, KeyError):
item = default
result.append(item)
return result
try:
return lst[idx]
except (IndexError, KeyError):
return default
[0, 1, 2]@get(slice(1, 4)) # [1, 2, None]
If itâs not useful, no need for big discussions. I have no investment in this apart from âitâs nice to me and itâs not taking any valuable space. What else are you going to do with slice type input here?â
Now I need first value in the list with a fallback. Then, if it is lower than 10, I need to take the 2nd with the fallback to 1st if it doesnât exist. With list.get: