-
-
Notifications
You must be signed in to change notification settings - Fork 31.9k
all(range()...)) is needlessley slow #81312
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Checking if a range's items are ll truthy can be done y checking if 0 the range contains 0, however currently Python iterates over the range, making the operation slower than needed. >>> rng = range(1, 1_000_000)
>>> timeit all(rng)
19.9 ms ± 599 µs per loop If the all function could special case range, this could be like made fast like this: if isinstance(obj, range):
if 0 in obj:
return False
return True |
Why should Should Personally, I don't *necessarily* oppose special-casing types, but it breaks the independence of types, and couples the all() function and the range() function. To be worth doing, we should get some practical benefit out of it. It isn't clear what that benefit is. Don't get me wrong, its not like I *want* all(range(1, 10**10)) to be slow. But nor do I want to couple the all() function to the range function and complicate the implementation if there is no corresponding benefit. After all, testing with all() is fundamentally an O(N) worst case operation so anything better than that is a nice surprise. If there were special dunders __all__ and __any__ it would be easy to encapsulate this behaviour inside the range objects themselves, and neither any() nor all() would need to know anything about range objects. |
Mostly to avoid silly mistakes, and the overhead of doing it would be very small, so a very small trade-off.
No,
No, I wouldn't propose that. The argument would be that those are iterators/generators while |
This sounds very interesting, and more general. It would be useful for e.g. numpy arrays, where |
What sort of silly mistakes?
Its not just the overhead, its the coupling between two chunks of code |
You can implement it yourself. _all = all
def all(obj):
if isinstance(obj, range):
return 0 not in obj
return _all(obj) I do not see reasons to do this in the stdlib. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: