Last active
January 13, 2023 21:47
-
-
Save James-E-A/103266855b91987114421d8f8e12c35b to your computer and use it in GitHub Desktop.
Python: iterable startswith()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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...)