In this post we will discuss how to sort list in Python.
There are mainly two ways to sort a list in Python.
This sort the given list and generate a new list, which means existing list won't be modified.
In : numbers = [23, 42, 12, 121, 45, 9, 8] In : sorted(numbers) Out: [8, 9, 12, 23, 42, 45, 121] In : numbers Out: [23, 42, 12, 121, 45, 9, 8]
As you can see in the above example
Out has the same numbers list.
This method applies the sorting on the list and updates the existing list. This is called in place sorting.
In : numbers.sort() In : numbers Out: [8, 9, 12, 23, 42, 45, 121]
sort methods takes an extra parameter called
key. Using this
key param we can control the sorting.
names = ['Bob', 'Charles', 'James']. Let's say we want to sort the above list of
names based on length of the each time.
In : sorted(names, key=len) Out: ['Bob', 'James', 'Charles']
We can pass any function we want to this
key. Let me know which method you like in the comments. If you like this content consider following me.