How to sort a list in Python

·

1 min read

In this post we will discuss how to sort list in Python.

There are mainly two ways to sort a list in Python.

  1. sorted function
  2. sort method

1. sorted function:

This sort the given list and generate a new list, which means existing list won't be modified.

In [1]: numbers = [23, 42, 12, 121, 45, 9, 8]

In [2]: sorted(numbers)
Out[2]: [8, 9, 12, 23, 42, 45, 121]

In [3]: numbers
Out[3]: [23, 42, 12, 121, 45, 9, 8]

As you can see in the above example Out[3] has the same numbers list.

2. sort method:

This method applies the sorting on the list and updates the existing list. This is called in place sorting.

In [4]: numbers.sort()

In [5]: numbers
Out[5]: [8, 9, 12, 23, 42, 45, 121]

Key param:

sorted and sort methods takes an extra parameter called key. Using this key param we can control the sorting.

Example: names = ['Bob', 'Charles', 'James']. Let's say we want to sort the above list of names based on length of the each time. Solution:

In [7]: sorted(names, key=len)
Out[7]: ['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.