Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing slices in python

Tags:

python

slice

Inspecting the slice class in Python with dir(), I see that it has attributes __le__ and __lt__. Indeed I saw that the following code works:

slice(1, 2) < slice(3, 4)
# True

However, I cannot see which logic is implemented for this comparison, nor its usecase. Can anyone point me to that?

I am not asking about tuple comparison. Even if slice and tuple are compared the same way, I don't think this makes my question a duplicate. What's more, I also asked for a possible usecase of slice comparison, which the suggested duplicate does not give.

like image 404
P. Camilleri Avatar asked Jun 15 '17 10:06

P. Camilleri


People also ask

How can I compare two slices?

To check if two slices are equal, write a custom function that compares their lengths and corresponding elements in a loop. You can also use the reflect. DeepEqual() function that compares two values recursively, which means it traverses and checks the equality of the corresponding data values at each level.

What is == comparing in Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and !=

How do you compare two items in a list Python?

The cmp() function is a built-in method in Python used to compare the elements of two lists. The function is also used to compare two elements and return a value based on the arguments passed. This value can be 1, 0 or -1.


1 Answers

Looking at the source code for slice reveals that the comparison is implemented by first converting the two objects into (start, stop, step) tuples, and then comparing those tuples:

https://github.com/python/cpython/blob/6cca5c8459cc439cb050010ffa762a03859d3051/Objects/sliceobject.c#L598

As to the use cases, I am not sure of the authors' intent. I do note that there don't appear to be any comparison unit tests for anything other than equality:

https://github.com/python/cpython/blob/6f0eb93183519024cb360162bdd81b9faec97ba6/Lib/test/test_slice.py#L87

like image 172
NPE Avatar answered Oct 15 '22 13:10

NPE