This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: add methods to get first and last elements of a range
Type: enhancement Stage: resolved
Components: Versions:
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: mark.dickinson, phr
Priority: normal Keywords:

Created on 2022-04-08 08:03 by phr, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg416962 - (view) Author: paul rubin (phr) Date: 2022-04-08 08:03
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.
msg416971 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2022-04-08 10:13
> but it's messy and potentially tricky to get the actual first and last values of the range

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
msg416973 - (view) Author: paul rubin (phr) Date: 2022-04-08 10:34
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.
History
Date User Action Args
2022-04-11 14:59:58adminsetgithub: 91413
2022-04-08 10:34:44phrsetstatus: open -> closed
resolution: rejected
messages: + msg416973

stage: resolved
2022-04-08 10:13:09mark.dickinsonsetnosy: + mark.dickinson
messages: + msg416971
2022-04-08 08:03:40phrcreate