Reputation: 609
In Python, I have the two lists of different sizes:
x = [[0,5,10],[0,10,5]]
y = [100,500,900]
What is the comparison happening at each step when I run:
print x>y
e.g. How does it compare say the first element: [0,5,10] vs 100?
Upvotes: 0
Views: 103
Reputation: 852
Essentially x == y
uses the magic __eq__
method on objects to compare them. Different objects will behave differently, and you can even define your own custom equalities, but in general comparing objects of different types will always evaluate to False
(Python2 and Python3 docs).
So in your example, [0,5,10] == 100
evaluates to False
, not because it checked to see if the elements in the list were equal to 100
, but because the two types were incompatible.
Upvotes: 0
Reputation: 2830
Just to expand on the other answers, the documentation is pretty good on this stuff. From the 2.7 documentation:
Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal.
From the 3.5 documentation:
Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one.
Upvotes: 0
Reputation: 122443
The real problem is how to compare [0,5,10]
vs 100
, i.e, a list vs an integer.
The answer depends on the Python version. In Python 3.x, the two types can't be compared. In Python 2.x, lists are always greater than integers because the type names list
is greater than int
.
In your example, the print
statement in
print x>y
suggests that you are using Python 2.x, so the answer is x > y
would be True
.
Upvotes: 1
Reputation: 184260
In Python 3, you can't compare those two lists because their elements are not of comparable types.
In Python 2, lists are always greater than integers, period, so your x
is always greater than your y
regardless of what elements are in x
's sublists.
Upvotes: 4
Reputation: 2520
Those comparisons won't work. list
and int
can't be compared. So it won't work
Upvotes: 0