Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python iterate slice object

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)
like image 627
Lucas Avatar asked May 20 '13 15:05

Lucas


People also ask

Can you slice an iterator in Python?

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.

Is Python slicing inclusive?

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.

When slicing in Python What does the 2 in [:: 2 specify?

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).

What is a slice object in Python?

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.


1 Answers

def FUNCTION_I_WANT(s, n):
  return range(*s.indices(n))
like image 145
Ignacio Vazquez-Abrams Avatar answered Oct 23 '22 05:10

Ignacio Vazquez-Abrams