Hello. I have a question while studying comparing two lists in Python.
num_1=[2,8,3,4,5]
num_2=[4,6,3,1,3]
print(num_1<num_2)
I wrote and executed the code like this, and True
was printed.
By the way, if you compare index 1 of the two lists, it is num_1>num_2
, so isn't it right if False
comes out?
num_1=[2,8,3,4,5]
num_2=[4,6,3,1,3]
class comparable_list(list):
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))
n1 = comparable_list(num_1);
n2 = comparable_list(num_2);
print(n1 < n2) # False
n3 = comparable_list([9,9,9,9,9]);
print(n1 < n3) # True
n4 = comparable_list([0,0,0,0,0]);
print(n1 > n4) # True
Le, ge, eq, ne are omitted
If you compare index 1 of the list, it is num_1>num_2 so
?
If you take out the first element and compare it, num_1[0](=2) < num_2[0](=4)
. Are you mistaken?
Compare by changing the list on the idle, etc. You'll understand.
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> [1] < [0]
False
>>> [1] < [2]
True
>>> [1] <= [1]
True
>>> [1] < [2, 1]
True
>>> [1] < [0, 333]
False
>>> [1] < ['1']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'
>>> ['1'] < ['2']
True
>>> [1] < [2, '3']
True
>>>
© 2024 OneMinuteCode. All rights reserved.