Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if an integer is an index value of a slice

Tags:

python

slice

Is there a Boolean function to test whether an integer is an index value contained in a slice object without unpacking the start, stop, and step parameters?

3 in slice(1, 6, 2)

raises an error as slices are not iterable.

The predicate should work for arbitrary None, start, stop, step parameters. The logic is straightforward but hoping there's a built in or package.

like image 396
alancalvitti Avatar asked Feb 22 '19 20:02

alancalvitti


People also ask

What does slice indices must be integers or none or have an __ index __ method?

The Python "TypeError: slice indices must be integers or None or have an __index__ method" occurs when we use a non-integer value for slicing (e.g. a float ). To solve the error, make sure to use integers when slicing a list, string or any other sequence. Here is an example of how the error occurs.

What is list indices must be integers or slices?

The Python "TypeError: list indices must be integers or slices, not float" occurs when we use a floating-point number to access a list at a specific index. To solve the error, convert the float to an integer, e.g. my_list[int(my_float)] .

What is the difference between indexing and slicing?

“Indexing” means referring to an element of an iterable by its position within the iterable. “Slicing” means getting a subset of elements from an iterable based on their indices.

How do I fix list indices must be integers or slices not str in Python?

The Python "TypeError: list indices must be integers or slices, not str" occurs when we use a string instead of an integer to access a list at a specific index. To solve the error, use the int() class to convert the string to an integer, e.g. my_list[int(my_str)] .


1 Answers

The logic is not as straightforward as you think, since it doesn't make sense to do this for a None stop or start (depending on the sign of step), since you need to specify a length.

Essentially, what you are asking for is containment in a range object, which holds the same information as a slice, but is a valid sequence, and supports fast containment checking. slice has a method called indices to help with the transformation, if you provide the length of the sequence you are interested in slicing:

def in_slice(n, s, length):
    return n in range(*s.indices(length))
like image 146
Mad Physicist Avatar answered Oct 04 '22 16:10

Mad Physicist