[Tutor] Sorting a list

Kent Johnson kent37 at tds.net
Thu May 14 12:02:53 CEST 2009


On Thu, May 14, 2009 at 3:34 AM, Timo <timomlists at gmail.com> wrote:
> Emile van Sebille schreef:

>> If this is always the case you can use the sort method of lists, then
>> relocate the last entry to the front --
>>
>> >>> a = [4, 6, 'word', 3, 9]
>> >>> a.sort()
>> >>> a.insert(0,a.pop())
>> >>> a
>> ['word', 3, 4, 6, 9]
>> >>>
>>
> Thanks all for your answers. I think I will go for this solution (should
> have come to it myself).

I don't think this will be reliable. IIUC unlike objects are compared
by ID, so it is not guaranteed that strings will sort after numbers.
The ability to compare unlike objects at all is considered a
mis-feature and has been removed in Python 3:
http://mail.python.org/pipermail/python-dev/2004-June/045111.html

Python 3.0.1 (r301:69556, Feb 14 2009, 22:08:17)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> a = [4, 6, 'word', 3, 9]
>>> a.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() < int()

Kent


More information about the Tutor mailing list