Why do dicts compare greater than any int? [duplicate] - python

This question already has answers here:
How does Python 2 compare string and int? Why do lists compare as greater than numbers, and tuples greater than lists?
(2 answers)
Closed 2 years ago.
My code accidentally compared a dict to an int using an inequality and it turns out that any dict evaluates True when tested to be greater than an int.
d = {'a': 1, 'b': 2}
d > 0
Out[20]: True
d > 10e99999999999999
Out[21]: True
Why does this happen instead of a type error?
This happens running on Python 2.7

From the Python 2.7 documentation:
Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result).
The Python 3.3 documentation has instead this:
The <, <=, > and >= operators will raise a TypeError exception when comparing a complex number with another built-in numeric type, when the objects are of different types that cannot be compared, or in other cases where there is no defined ordering.
Meaning what you are seeing is no longer possible as of Python 3, but instead such comparisons yield a TypeError like you expected.

First, the Python team agrees with you -- in Python 3, this is an error.
In earlier Python versions everything is comparable with each other, to make it consistent some types always sort before other types.

Apparently in Python 2.7 Dictionaries are always greater than integers. Apparently it's alphabetical?

Related

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

This question already has answers here:
How does Python 2 compare string and int? Why do lists compare as greater than numbers, and tuples greater than lists?
(2 answers)
Closed 6 years ago.
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"]?
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.
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__.
According to this, different types just have to compare unequal, it's up to the implementation to decide how to handle that. It just so happens that CPython's implementation decides to order based on type names.

Why does max() return an empty list as the largest item (larger than integers) [duplicate]

This question already has answers here:
How does Python 2 compare string and int? Why do lists compare as greater than numbers, and tuples greater than lists?
(2 answers)
Closed 4 years ago.
I have discovered that a list is greater than a number.
>>> [1,2,3] > 1000
True
Is there some reason why this works? I can't convert a list to an int with int([1,2,3]). The int can't be converted to a list with list(1000). So how is python comparing the two?
In this case of "mismatched" types, the types are listed lexicographically by type name: a "list" comes after an "int" in alphabetical ordering, so it is greater.
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.
(source)
There is no language specification for the ordering (apart from the fact that it is consistent). It just happens to be the case that CPython is the most common implementation in which there is this language detail of being ordered lexicographically by type names.
According to the Python Reference Manual,
Most other objects of built-in types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program.

Test if two lists are equal [duplicate]

This question already has answers here:
Check if two unordered lists are equal [duplicate]
(8 answers)
Closed 7 years ago.
I'm trying to write tests for my Django app and I need to check many times
if 2 lists have the same objects (i.e. that every object in A is also in B and vice versa).
I read on the assertLists/Sequence/Equal etc but for what I saw if the lists
have the same objects but in a different order (A = [a,b,c], B = [b,c,a]) then it returns an error, which I don't want it to be an error because they both have the same objects.
Is there a way to check this without looping the lists?
You can use assertCountEqual in Python 3, or assertItemsEqual in Python 2.
From the Python 3 docs for assertCountEqual:
Test that sequence first contains the same elements as second, regardless of their order. When they don’t, an error message listing the differences between the sequences will be generated.
Duplicate elements are not ignored when comparing first and second. It verifies whether each element has the same count in both sequences. Equivalent to: assertEqual(Counter(list(first)), Counter(list(second))) but works with sequences of unhashable objects as well.
If you are staying with list() datatype then the cleanest way if your lists are not too large would be :
sorted(list_1) == sorted(list_2)
Have a look at this Question (which is the same):
Check if two unordered lists are equal

internal comparison of string and int in python [duplicate]

This question already has answers here:
How does Python 2 compare string and int? Why do lists compare as greater than numbers, and tuples greater than lists?
(2 answers)
Closed 2 years ago.
When a string is being compared to an integer are the string and int compared with the ASCII code internally, or how is it? I know that strings compare greater than integers, but how does that internal comparison takes place?
>>> "a" > 1
True
In your example, 1 < "a" because "i" for int comes alphabetically before "s" for string.
From the docs:
Objects of different types, except different numeric types and
different string types, never compare equal; such objects are ordered
consistently but arbitrarily (so that sorting a heterogeneous array
yields a consistent result).
I believe this was one of the things changed in python 3 (you would get a TypeError here).
As for how it is done in CPython, 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. Note that this is part of the implementation, not a part of the language.
You should check the source of the __gt__ method of the inbuilt string object to know the details but my guess is that the 1 is converted to a string using the str function and then then the two are compared.

Why are Python objects of different types ordered by type names? [duplicate]

This question already has answers here:
Why is '' > 0 True in Python 2?
(2 answers)
Closed 2 years ago.
From Python docs: http://docs.python.org/library/stdtypes.html#comparisons
Implementation note: 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.
Is there any reason for choosing to do this over raising an exception?
About four lines up from that line you quoted:
Objects of different types, except
different numeric types and different
string types, never compare equal;
such objects are ordered consistently
but arbitrarily (so that sorting a
heterogeneous array yields a
consistent result).
You don't want to raise exceptions when sorting a list of differently typed objects.
It can be useful for objects of different types to be collected into a single, sorted list, in a definite order. By giving all objects a stable sort order, this behavior is default.

Categories

Resources