[Python-ideas] Allow callables in slices

Steven D'Aprano steve at pearwood.info
Sat Jun 9 05:47:57 EDT 2018

On Sat, Jun 09, 2018 at 11:17:05AM +0200, Michel Desmoulin wrote:
> Such as that:
>     def starting_when(element):
>         ...
>     a_list[starting_when:]

> Is equivalent to:
>     list(dropwhile(lambda x: not starting_when(x), a_list))

That looks like a slice from an index to the end of the list. Things 
which are similar should look similar, but things which are different 
should NOT look similar.

What would:


do? How about this one?


If there are not meaningful interpretations of callables as part of 
general slice notation, then we shouldn't use slice notation as a 
shortcut for dropwhile.

Rather than give this syntactic support, I'd rather add a new function 
to itertools that composes takewhile and dropwhile:

def between(iterable, startcondition, endcondition):
    it = iter(iterable)
    return takewhile(lambda x: not endcondition(x), 
           dropwhile(lambda x: not startcondition(x), it)

If the caller wants to convert to a list (or some other sequence), they 
can, otherwise they can keep it as an iterator.


More information about the Python-ideas mailing list