Python Forum

Full Version: Basic question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
my question here
Hi,
I am new to python. Please explain the below. Why one syntax is returning "True" while the second one returns False.

>>> print "[1, 2] > 'foo' = ", (1, 2) > 'foo'
[1, 2] > 'foo' = True
>>> print "[1, 2] > 'foo' = ", [1, 2] > 'foo'
[1, 2] > 'foo' = False
>>>

Thanks

my code here
Both of these statements will return a syntax error.
Nope. As you see above, one is "True" and the second one is "False"
In Python 2.x, yes. But in Python 3.x this creates a TypeError. Ordering of disparate types was something that was dropped in Python 3.x, precisely because of screwy stuff like this that doesn't make any sense. You should switch to Python 3.x if you can.
sorry, I just got up, and didn't realize you were using python 2.7

 >>> print "[1, 2] > 'foo' = ", (1, 2) > 'foo' 
I'm not sure exactly how 2.7 compares tuples against strings,
but the ASCII value of 'f' is 102, which is greater than either 1 or 2,
so I would expect it to return False. It shouldn't even allow this comparison
Python 3 gives the following error:

 >>> print("[1, 2] > 'foo' = ", ((1, 2) > 'foo')) 
Error:
>>> print("[1, 2] > 'foo' = ", ((1, 2) > 'foo')) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: '>' not supported between instances of 'tuple' and 'str' >>>
The second one:
print "[1, 2] > 'foo' = ", [1, 2] > 'foo'
gives the following error in python 3:
Error:
>>> print ("[1, 2] > 'foo' = ", [1, 2] > 'foo') Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: '>' not supported between instances of 'list' and 'str' >>>
my suggestion upgrade to python 3.6.2
Acording to Python 2.x documentation:
Quote:Objects of different types except numbers are ordered by their type names

This will throw an error in Python 3

So it seems like you a doing comparison between 'tuple' and 'str'. 't' is greater than 's'
Thanks. (1,2) is tuple. What is [1, 2]...a list?
Yes, [1, 2] is a list. So 'l' is less than 's'.
Thanks a lot