Getting Started with Sort in Python: Sorting Lists in-place

Let us starting simple and start with easy sort. Python has two sort functions; one function that sorts a list in-place and the other sort function “sorted” that creates a new sorted list. In this post, we will see examples of “in-place” sorting.

Python’s in-place sorting

As the name suggests the in-place sorting replaces the original un-sorted list to a new sorted list. If you have a list named myList and want to sort it using in-place sorting,

just call the built-in method as myList.sort()

For example,

>>> myList = [66,11,88, 44, 77]
>>> myList.sort()
>>> myList
[11, 44, 66, 77, 88]

Remember, myList can contain a numbers or strings. For example, if you are sorting strings, Python will sort it alphabatically as

>>>myList=["line", "cmd", "tips"]
>>>myList.sort()
>>>myList
['cmd', 'line', 'tips']

Often you might have numbers as string and you might want to sort numerically. However, Python will do it alphabatically. For example, if you sort the list

>>> myList = ["50", "111", "1", "99", "10"]

Python will do the sort alphabatically and give you

>>> myList.sort()
>>> myList
['1', '10', '111', '50', '99']

If you really want to sort the string list by treating it as numeric, you can use the option “key” in Python sort function as

>>> myList = ["50", "111", "1", "99", "10"]
>>> myList.sort(key=int)
>>> myList
['1', '10', '50', '99', '111']

Often you will want to sort a list of strings based on some specific criteria in the string (a specific part of the string). One way to do is to use lambda function. For example a list with with numeric values as part of the string.

  myList =["cmd1","cmd10", "cmd111", "cmd50", "cmd99"]

Using myList.sort() will sort the list alphabatically.

>>> myList.sort()
>>> myList
['cmd1', 'cmd10', 'cmd111', 'cmd50', 'cmd99']

To sort the list according the numeric value in each of string in the list, use

>>> myList =["cmd1","cmd10", "cmd111", "cmd50", "cmd99"]
>>> myList.sort(key=lambda x: int(x[3:]))
>>> myList
['cmd1', 'cmd10', 'cmd50', 'cmd99', 'cmd111']

where the key is a lambda function that takes string as input and the numeric value as output.

Here is one more example of sorting lists using lambda function. Again we will be sorting a list of string based on part of string.

>>> myList =["cmd_line1","cmd_line10.com", "cmd_line111", "cmd_line50", "cmd_line99"]
>>> 
>>> myList.sort(key=lambda x: lambda x: int(x.split("_")[1][4:]))
>>> myList
['cmd_line1', 'cmd_line10.com', 'cmd_line111', 'cmd_line50', 'cmd_line99']