You are re-assigning the list on line 4 here, not displaying it. I get the answer you expect when using the `itemgetter(0)` key:

IPython 7.28.0, on CPython 3.9.7 (default, Aug 31 2021 13:28:12)
>>> import operator
>>> from operator import itemgetter
>>> L = [(1, 'a'), (2, 'b'), (1, 'c'), (2, 'd'), (3, 'e')]
>>> L.sort(key=operator.itemgetter(0), reverse=True)
>>> L
[(3, 'e'), (2, 'b'), (2, 'd'), (1, 'a'), (1, 'c')]

On 10/30/21 12:47, Raymond Bisdorff wrote:
Dear All,

I fully agree with your point. By default, all the components of the tuple should be used in the comparison.

Yet, I was confused by the following result.
>>> from operator import itemgetter
>>> L = [(1, 'a'), (2, 'b'), (1, 'c'), (2, 'd'), (3, 'e')]
>>> L.sort(key=itemgetter(0), reverse=True)
>>> L = [(3, 'e'), (2, 'd'), (2, 'b'), (1, 'c'), (1, 'a')]

Should the tuples comparison is in this case, I thought, not be solely based on the first tuple component?
Best Regards

On 10/30/21 18:26, Tim Peters wrote:
[Raymond Bisdorff <raymond.bisdo...@pt.lu>]
...
Please notice the following inconsistency in Python3.10.0 and before of
a sort(reverse=True) result:

  >>> L = [(1, 'a'), (2, 'b'), (1, 'c'), (2, 'd'), (3, 'e')]
  >>> L.sort(reverse=True)
  >>> L
  >>> [(3, 'e'), (2, 'd'), (2, 'b'), (1, 'c'), (1, 'a')]
Looks good to me.

it should be:

  >>> L = [(1, 'a'), (2, 'b'), (1, 'c'), (2, 'd'), (3, 'e')]
  >>> reverseTuplesSort(L)
[(3, 'e'), (2, 'b'), (2, 'd'), (1, 'a'), (1, 'c')]
Stability is irrelevant in the example, because no two list elements
are equal. You appear to be thinking, perhaps, that s[0] == t[0] when
s == (1, 'a') and t == (1, 'c') means s and t "are equal", but that's
not so at all.

s = (1, 'a')
t = (1, 'c')
s == t
False
s < t
True
t > s
True

So s MUST come before t in a forward sort, and t MUST come before s in
a reverse sort.


_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/python-dev@python.org/message/LRERVUWNU2FABB2KRKV2KPHAG2UBKFXI/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to