I've been trying to work out why my AI has been making some crazy moves and I traced the problem back to the following behaviour when using Python 2.7.2
>>> print [2]>[1]
True
>>> print (2,)>(1,)
True
>>> print [2]>(1,)
False (WHY?)
>>> print [2]<[1]
False
>>> print (2,)<(1,)
False
>>> print [2]<(1,)
True (WHY?)
It seems to behave as if lists are always less than tuples.
This is not what I expected from the documentation
Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.
If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]).
What is going on here? Am I allowed to compare tuples and lists - or perhaps am I only allowed to compare the same type with itself?
As for why 1.0 == 1 , it's because 1.0 and 1 represent the same number. Python doesn't require that two objects have the same type for them to be considered equal.
Indexing in Python In Python, indexing is zero-based. This means the first element has 0 as its index, the second element has 1 as its index, and so on. Let's demonstrate indexing with lists. Here we have a list of numbers from which we want to access the 1st and 2nd elements.
== 0 means "equal to 0 (zero)". So if foo == 0: means "do the following if foo is equal to 0", thus if x % 2 == 0: means "do the following if x % 2 is equal to 0". Follow this answer to receive notifications.
Python has a “greater than but less than” operator by chaining together two “greater than” operators. For example, the expression 5 < x < 18 would check whether variable x is greater than 5 but less than 18.
Sequences are not coerced when comparing, hence their type name is compared instead.
>>> 'list' < 'tuple'
True
They're not the same type.
each element must compare equal and the two sequences must be of the same type and have the same length
So the comparison is being performed based on type, not on actual data stored in the sequences. On python3.x, this comparison raises a TypeError
:
Python 3.2 (r32:88445, May 11 2011, 09:23:22)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> [2] > (1,)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: list() > tuple()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With