-
Notifications
You must be signed in to change notification settings - Fork 2.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Element-wise comparison for lists #324
Comments
The same result is obtained in JavaScript. > [0, 0, 0] <= [255, 123, 5] && [255, 123, 5] <= [255, 255, 255]
true
> [0, 0, 0] <= [256, 123, 5] && [256, 123, 5] <= [255, 255, 255]
false
> [0, 0, 0] <= [255, 123, -5] && [255, 123, -5] <= [255, 255, 255]
true
> [0] <= [-5] && [-5] <= [255]
false
> ([0, 0, 0] <= [255, 123, -5]) && ([255, 123, -5] <= [255, 255, 255])
true
> [0, 0, 0] <= [-5, 123, 2555] && [-5, 123, 2555] <= [255, 255, 255]
false |
Python uses the lexicographic order, same as C++ and most languages really. |
As shiracamus and lezcano have already mentioned, pretty much every other language uses the same implementation as it is consistent with the general idea of lexicographical ordering. If you really want you could create a custom class and maybe override how the comparison operators work for specific use case. class CustomList(list):
def __le__(self, other):
return all(x <= y for x, y in zip(self, other))
def __ge__(self, other):
return all(x >= y for x, y in zip(self, other))
def __lt__(self, other):
return all(x < y for x, y in zip(self, other))
def __gt__(self, other):
return all(x > y for x, y in zip(self, other))
def test_custom_list():
assert CustomList([0, 0, 0]) <= CustomList([255, 123, 5]) <= CustomList([255, 255, 255])
assert not CustomList([0, 0, 0]) <= CustomList([256, 123, 5]) <= CustomList([255, 255, 255])
assert CustomList([0, 0, 0]) <= CustomList([255, 123, -5]) <= CustomList([255, 255, 255])
assert not CustomList([0]) <= CustomList([-5]) <= CustomList([255])
assert not CustomList([0, 0, 0]) <= CustomList([-5, 123, 2555]) <= CustomList([255, 255, 255])
# You can run these test cases
test_custom_list() In this example, I created a Custom class that inherits from the built-in list class and overrides the less than or equal (le), greater than or equal (ge), less than (lt), and greater than (gt) comparison methods. |
Hey @satwikkansal , what are your thoughts about this snippet? Should it be included in |
I agree with others that the behavior is consistent across programming languages. It's not a surprising behaviour, although I think it's still a good piece to include with the following changes;
|
It seems that Python will only compare the first elements of each list and continue.
The text was updated successfully, but these errors were encountered: