Hacker News new | past | comments | ask | show | jobs | submit login

In Python, when comparing lists using the less than (<) operator, the comparison is performed element-wise.

The first element of each list is compared, and if they are not equal, the comparison result is determined based on the comparison of the first unequal elements.

In this case, [1, 2] and [10, 2] both have different first elements (1 and 10). Since 1 is less than 10, the comparison result is True.

The second element of both lists (2) does not affect the comparison result because the first element is already sufficient to determine the outcome.

[1, 2] < [10, 2] evaluates to True.




All of these could be equally valid results of your list comparison: True, False, [True, False], [[True, True], [True, False]].

I like that typescript does not rely on an implicit choice, but let’s me express exactly what comparison I care about.


I agree there are a few versions you could do, but most languages tend to do lexicographic.

This has been a suprising thread to me -- I just assumed "everyone knew" that the vast majority of languages do lexicographic comparision of lists.

I will say typescript does "rely on an implicit choice", it has a default implement (the "convert to string"), which I'm going to be honest, doesn't ever seem like a sensible choice to me -- although maybe it feels more natural to javascript/typescript people.

My personal upset (I lost like a day to this) is that if you keep your numbers under 10, you do get the lexicographic ordering, as then lexicographic = string. I had a bunch of unit tests (all using numbers under 10), just larger inputs kept breaking, and it didn't occur to me to go read the docs for < :)


What's the use case for this?


Lots of mathematical algorithms sort lists lexicographically. It comes up in graphs and lots of other combinatorics problems. Often you want a total order on 2D coordinates, an this ordering is (usually) the simplest and best.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: