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: range() function could accept slice() objects as parameters
Type: enhancement Stage:
Components: Interpreter Core Versions: Python 3.11
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: rhettinger, serhiy.storchaka, yota moteuchi
Priority: normal Keywords:

Created on 2022-01-09 12:36 by yota moteuchi, last changed 2022-04-11 14:59 by admin.

Messages (2)
msg410143 - (view) Author: yota moteuchi (yota moteuchi) Date: 2022-01-09 12:36
This improvement proposal is close to : https://bugs.python.org/issue42956 and also detailed in https://stackoverflow.com/questions/13855288/turn-slice-into-range

to iterate over a slice, the recommended method seems to be : 

s = slice(5,100,3)
for i in range(s.stop)[s] :
    # do something

but if range() accepted directly a slice, it would dramatically improve the readability :

s = slice(5,100,3)
for i in range(s) :
    # do something

and it could be convenient, especially inside the __getitem__ property. I'll try to make a quick patch to test...
msg410147 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2022-01-09 13:51
Accepting a slice directly in the range constructor is ambiguous. What to do if start or stop are negative or None? What if stop is less than start? You need to specify a sequence length to handle these cases.

Maybe the following expressions work for you:

   range(length)[s]

or

   range(*s.indices(length))

But other users may need different behavior (if they want convert slice(-20, -10) to range(-20, -10)). There is no general solution which would work for all, you have to code what you need.
History
Date User Action Args
2022-04-11 14:59:54adminsetgithub: 90470
2022-01-09 13:51:12serhiy.storchakasetnosy: + rhettinger, serhiy.storchaka
messages: + msg410147
2022-01-09 12:47:58yota moteuchisetcomponents: + Interpreter Core, - Library (Lib)
2022-01-09 12:46:20yota moteuchisetcomponents: + Library (Lib)
2022-01-09 12:36:50yota moteuchicreate