If I have a slice object
s = slice(a,b,c)
and an array length n
, is there a nice readymade iterator for the elements so that I can do something like:
for index in FUNCTION_I_WANT(s, n):
do_whatever(index)
and have it behave like slicing of lists, beyond the really horrible:
def HACKY_VERSION_OF_FUNCTION_I_WANT(s,n):
yield range(n).__getitem__(s)
Slicing Iterables in Python. Python slicing allows you to access a range of elements from an iterable. For instance, you can get the first three numbers from a list of numbers with slicing.
Python is a zero-indexed language (things start counting from zero), and is also left inclusive, right exclusive you are when specifying a range of values. This applies to objects like lists and Series , where the first element has a position (index) of 0.
Therefore, the elements before the stop sign are returned. Second note, when no start is defined as in A[:2] , it defaults to 0. There are two ends to the list: the beginning where index=0 (the first element) and the end where index=highest value (the last element).
Python slice() Function A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.
def FUNCTION_I_WANT(s, n):
return range(*s.indices(n))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With