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
add methods to get first and last elements of a range #91413
Comments
Inspired by a question on comp.lang.python about how to deal with an int set composed of integers and ranges. Range objects like range(1,5,2) contain start, stop, and step values, but it's messy and potentially tricky to get the actual first and last values of the range. Examples: range(1,5,2) - first = 1, last = 3 range (5, 1, 2) - range is empty, first = last = None range(5, 1, -1) - first is 5, last is 2 Note in the case where the range is not empty, you can get the "last" by a messy calculation but it's easier to pick the first element from the reverse iterator. But then you might forget to catch the stopiteration exception in the case that the list is empty. The same goes for the first element, roughly. And constructing the iterators just to pick one element seems like unnecessary overhead. So it is better to have actual methods for these, with type Optional[int]. Then mypy should remind you to check for the empty case if you forget. |
Doesn't simple indexing already provide what you need here? >>> range(1, 5, 2)[0] # first element of range
1
>>> range(1, 5, 2)[-1] # last element of range
3 |
Oh nice, I didn't realize you could do that. len(range) and bool(range) (to test for empty) also work. Ok I guess this enhancement is not needed. I will close ticket, hope that is procedurally correct, otherwise feel free to fix. Thanks. |
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: