Python: How to Sort a List (Strings / Numbers)

By Punit Bhatt on Oct 24, 2020

Python sorting functionality offers robust features to do basic sorting or customize ordering at a granular level.

In this Article, you’ll learn how to sort various types of data in different data structures, customize the order, and work with two different methods of sorting in Python.

Using sort() Function

In Python, List has a native function to sort its items - sort() function. It can be used in different use-cases to sort the list. It is a very powerful function and can do custom sorting too by providing lambda function.

Key Note:

  • The sort() function modifies the list in-place, therefore the list itself is modified and the function has no return value.
  • It is a method of the *list *class and therefore can only be used with lists.
  • By default, it sorts in ascending order

Sort List containing numbers (Integers and decimals)

Let's review an example of sorting a list containing numbers. Sorting integers is quite simple as it compares using comparison operator and sorts accordingly.

Numbers = [1,32,8.4,5]

Make sure all items are numbers since number and string cannot be compared via comparison operator "<".

Sort List containing strings

The sort() function can also be used to sort strings and it is quite robust as it not only compares first character, but subsequent characters if previous ones are same.

Let's review one simple example:

Flowers = ["rose", "lotus", "lily", "sunflower"]
#['lily', 'lotus', 'rose', 'sunflower']

What if you want to compare only specific index in strings? That complex huh?

Let's try to sort 3 phrases by 2nd character in third word of each phrase!

phrases = [ 'Barking Up The Wrong Tree' ,'Give a Man a Fish', 'A Fool and His Money are Soon Parted' ]
phrases.sort(key=lambda x: x.split()[2][1])
# ['Give a Man a Fish', 'Barking Up The Wrong Tree', 'A Fool and His Money are Soon Parted']

Here, we are using key parameter of sort function and providing a lambda function to extract 2nd character of 3rd word in each phrase and use it to sort the list. Pretty clever!

Strings are case-sensitive!

When sorting strings, you also need to pay attention to case since when sorting, sort() method sorts character using ASCII character, therefore Uppercase characters comes before lowercase in sorting.

Let's review an example:

Flowers = ["rose", "lotus", "lily", "Sunflower"]
#['Sunflower', 'lily', 'lotus', 'rose']

Sort list in reverse order using sort()

As sort() orders the list in ascending order by default, if you want to sort the list in descending order, you need to provide the order state as parameter.

Let's see how we can sort the list in descending order:

Numbers = [1,32,8.4,5]
#[32, 8.4, 5, 1]

Using sorted() Function

Python also provides built-in function sorted() to sort all types of iterable data types like - lists, tuples, sets etc.

The sorted() and sort() are kind of similar with few differences. Therefore, either of them can be used to sort the list. We already talked about sort() function, so let's talk about sorted().

Key Note:

  • The sorted() method does not sort the list in-place. Therefore, it does not modify the list itself rather it returns new sorted list.
  • It is a built-in method in python thus can be used on any kind of iterable variable including lists, tuples and sets
  • By default, it sorts in ascending order

Sort Numbers using sorted()

Just like sort() function, we can sort numbers list using sorted() as well.

Let's review an example:

Numbers = [1,32,8.4,5]
sortednumbers = sorted(Numbers)

Similarly, you can sort list of strings as well using sorted() function.

Sort List with a key argument

Just like with sort() method, you can use key argument to customize sort logic when sorting a list.

Let's try sorting the list of strings by length of the strings from smallest to biggest string:

Flowers = ["rose", "lotus", "lily", "sunflower"]
sortedlist = sorted(Flowers, key=len)
# ['rose', 'lily', 'lotus', 'sunflower']

Two things to note in above example:

  1. We are passing len function to key parameter, therefore sorting function gets length of each string using len function and compares length of each string.
  2. The strings 'rose' comes before 'lily'. Why? Since, we are sorting only by length, sorting function won't change the order if length of strings are same. Therefore, 'rose' and 'lily' would remain as it is. In normal sorting, 'lily' would come before 'rose' in ascending order.

Useful Tip:

As we talked above, sorting list contained strings with both uppercase and lowercase is problematic. How to fix that?

Sort list containing both uppercase and lowercase strings

Remember, both sort() and sorted() function allows us to customize sorting functionality using key parameter.

Thus, we will use key argument, and will lowercase all strings before sorting them using str.lower function.

Not to worry about data mutation as key argument won't actually modify our strings.

stringlist = ["rose", "lotus", "lily", "Sunflower"]
sortedlist = sorted(stringlist)
# ['Sunflower', 'lily', 'lotus', 'rose']  ==> OOPS

# Let's fix it
stringlist = ["rose", "lotus", "lily", "Sunflower"]
sortedlist = sorted(stringlist, key=str.lower)
# ['lily', 'lotus', 'rose', 'Sunflower']