Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create range from tuple (slice.indices())

At the bottom of this page from the Python 2.3 docs it says:

slice objects now have a method indices(length) which, given the length of a sequence, returns a (start, stop, step) tuple that can be passed directly to range()

Here is some test code:

s = slice(0, 10)
r = range(s.indices(10))

It throws a TypeError:

TypeError: range() integer end argument expected, got tuple.

Why doesn't this work?

In my use case, range() is called in a library and I need to supply a slice that is used this way.

like image 825
Toast Avatar asked Mar 06 '26 00:03

Toast


1 Answers

Try this:

r = range(*s.indices(10))

Explanation: range() expects up to three integers as arguments, so we need to unpack the tuple of integers returned by indices() using *, the splat operator.

like image 153
Óscar López Avatar answered Mar 07 '26 13:03

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!