Greater and less than operators [was Re: [Tutor] beginning to code]

Steve D'Aprano steve+python at pearwood.info
Wed Sep 20 23:01:42 EDT 2017


On Thu, 21 Sep 2017 10:16 am, Rick Johnson wrote:

>> You've never wanted to sort strings? How do you sort
>> strings unless you have a concept of which string comes
>> before the other, i.e. < operator?
>> 
>> >>> 'xyz' < 'abc'
>> False
> 
> Interesting. But now we need to learn yet another set of
> arbitrary rules. Consider this:
> 
>     >>> 'azzz' > 'zzz'
>     False
>     
> Now, i'm not sure how Python decided that 'azzz' is not
> greater than 'zzz'

Because 'a' comes before 'z' in the alphabet.

Come now Rick, surely you're pulling my leg. This is plain old lexicographical
order, otherwise known as "alphabetical order", as taught by schools and used
by dictionaries, alphabetical indexes, phone books, book libraries and more,
for probably the last 200 years.

https://en.wikipedia.org/wiki/Lexicographical_order

In case you need a refresher:

https://www.spellingcity.com/games/alphabetize.html

The only difference here is that Python, like nearly all other programming
languages, orders the characters by their ordinal value rather than comparing
them strictly by case-insensitive alphabetical order.


>> Same applies to lists of items. Provided the items are
>> compatible with ordering, so are the lists. Likewise other
>> sequences.
> 
> But how are we to intuit the arbitrary rules?

Lists and tuples use the same lexicographic ordering as strings, except that
lists accept arbitrary object not just characters. So long as each pair of
objects in corresponding positions can be compared, the whole list can be
compared too.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list