Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python 2 allow comparisons between lists and numbers? [duplicate]

I recently discovered a typo in my program

while len(first_list) > second_list:
    do_stuff

I played around with this and discovered that 5 < ["apple"] == True and 5 > ["apple"] == False

Why does Python allow these sorts of comparisons? What is being evaluated under the hood to determine that 5 is less than ["apple"]?

like image 243
Trajanson Avatar asked Dec 03 '16 08:12

Trajanson


People also ask

How do you compare values in two lists in 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.

Can we compare two lists in Python?

We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.

How do you check if two sets have the same element in Python?

Another approach to find, if two lists have common elements is to use sets. The sets have unordered collection of unique elements. So we convert the lists into sets and then create a new set by combining the given sets. If they have some common elements then the new set will not be empty.


2 Answers

I think that the types are compared in this case, so it's like writing:

type(5) < type(["apple"])

and since "int" and "list" are compared lexicographically ("i" < "l"), you're getting this output.

If you try:

"5" > ["apple"]

you'll get False, since "string" > "list".

Documentation:

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

like image 100
Maroun Avatar answered Sep 19 '22 03:09

Maroun


Its from documentation of python 2:

The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-builtin types by defining a __cmp__ method or rich comparison methods like __gt__.

like image 20
salmanwahed Avatar answered Sep 20 '22 03:09

salmanwahed