Skip to content

Instantly share code, notes, and snippets.

@James-E-A
Last active January 13, 2023 21:47
Show Gist options
  • Save James-E-A/103266855b91987114421d8f8e12c35b to your computer and use it in GitHub Desktop.
Save James-E-A/103266855b91987114421d8f8e12c35b to your computer and use it in GitHub Desktop.
Python: iterable startswith()
from operator import eq as _eq
from itertools import starmap as _starmap, chain as _chain, repeat as _repeat
def _istartswith(a, b):
"""
Returns True if every element of b is equal to the zip-corresponding element of a;
returns False otherwise, including in the event that a has fewer elements than b.
"""
return all(_starmap(_eq, zip(_chain(a, _starmap(object, _repeat(()))), b)))
@James-E-A
Copy link
Author

The difference is not huge, but some non-rigorous testing shows that, regardless of whether 1 or 0 items is consumed, _starmap(object, ())) is definitely faster than _repeat(object())) (and even than _starmap(object, [])), though by a smaller margin).

Obviously, the calculus on this will change quite quickly in other contexts—such as when consuming more than 1 item—but this function will obviously consume at most 1 item, making this a clear choice.

(Now, the question of whether using a naked object() as an always-unequal token is the appropriate solution here or a giant kludge is separate...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment