Skip to content

Effortlessly Sort Strings in Python


How to Use sorted() and .sort() in Python

by David Fundakowski

All programmers will have to write code to sort items or data at some point. Sorting can be critical to the user experience in your application, whether it’s ordering a user’s most recent activity by timestamp, or putting a list of email recipients in alphabetical order by last name. Python sorting functionality offers robust features to do basic sorting or customize ordering at a granular level.

In this guide, 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.

By the end of this tutorial, you’ll know how to:

  • Implement basic Python sorting and ordering on data structures
  • Differentiate between sorted() and .sort()
  • Customize a complex sort order in your code based on unique requirements

For this tutorial, you’ll need a basic understanding of lists and tuples as well as sets. Those data structures will be used in this tutorial, and some basic operations will be performed on them. Also, this tutorial uses Python 3, so example output in this tutorial might vary slightly if you’re using Python 2.

Ordering Values With sorted()

To get started with Python sorting, you’re first going to see how to sort both numeric data and string data.

Sorting Numbers

You can use Python to sort a list by using sorted(). In this example, a list of integers is defined, and then sorted() is called with the numbers variable as the argument:

numbers = [6, 9, 3, 1]

The output from this code is a new, sorted list. When the original variable is printed, the initial values are unchanged.

This example shows four important characteristics of sorted():

  1. The function sorted() did not have to be defined. It’s a built-in function that is available in a standard installation of Python.
  2. sorted(), with no additional arguments or parameters, is ordering the values in numbers in an ascending order, meaning smallest to largest.
  3. The original numbers variable is unchanged because sorted() provides sorted output and does not change the original value in place.
  4. When sorted() is called, it provides an ordered list as a return value.

This last point means that sorted() can be used on a list, and the output can immediately be assigned to a variable:

numbers = [6, 9, 3, 1]
numbers_sorted = sorted(numbers)

In this case, the numbers_sorted variable will contain the sorted list [1, 3, 6, 9].

Sorting Strings

Sorting strings with sorted() works similarly to sorting numbers. In this example, a list of strings is defined, and sorted() is called with the names variable as the argument:

names = ["Alice", "Charlie", "Bob", "Dan"]

The output is a new, sorted list of strings ordered alphabetically:

['Alice', 'Bob', 'Charlie', 'Dan']

Like before, the original names variable is unchanged. And just like sorting numbers, the sorted() function can be used on a list and the output assigned to a new variable:

names = ["Alice", "Charlie", "Bob", "Dan"]
names_sorted = sorted(names)

The names_sorted variable will contain the sorted list [‘Alice’, ‘Bob’, ‘Charlie’, ‘Dan’].

Limitations and Gotchas With Python Sorting

While sorting in Python is powerful, there are some limitations and gotchas to be aware of. Let’s explore a couple of them.

Lists With Non-Comparable Data Types Can’t Be sorted()

Python lists are flexible and can contain different types of data in the same list. However, if a list contains non-comparable data types, such as a mixture of numbers and strings, the sorted() function will raise a TypeError:

mixed_data = ['Alice', 3, 'Bob', 1]

This code will raise a TypeError with the message “unorderable types: int() < str()“. To successfully sort a list with mixed data types, you would need to convert the elements to a common data type first.

When You’re Sorting Strings, Case Matters

By default, Python sorting is case-sensitive. This means that uppercase letters are considered to be “less than” lowercase letters. For example, in the following code, ‘Zebra’ comes before ‘apple’ when the list is sorted:

animals = ['cat', 'Zebra', 'apple', 'Bat']

The output will be:

['Bat', 'Zebra', 'apple', 'cat']

If you want to sort strings in a case-insensitive manner, you can provide an optional key argument to sorted() that converts all strings to lowercase before sorting. This can be achieved using str.lower as the key function:

animals = ['cat', 'Zebra', 'apple', 'Bat']
sorted(animals, key=str.lower)

The output in this case will be:

['apple', 'Bat', 'cat', 'Zebra']

Using sorted() With a reverse Argument

In addition to sorting in ascending order, you can also sort in descending order using the reverse argument. The reverse argument is a boolean value that determines whether the list should be sorted in reverse or not. By default, it is set to False, resulting in ascending order. To sort a list in descending order, pass True as the reverse argument:

numbers = [6, 9, 3, 1]
sorted(numbers, reverse=True)

The output will be:

[9, 6, 3, 1]

sorted() With a key Argument

Python’s sorted() function allows you to further customize the sort order using the key argument. The key argument specifies a function that takes an element from the iterable and returns a value that is used for sorting. In this way, you can specify a custom sort order based on specific criteria.

For example, consider a list of strings representing people’s names. To sort them by the length of the name instead of the default alphabetical order, you can define a key function that returns the length of each name:

names = ['Alice', 'Charlie', 'Bob', 'Dan']
sorted(names, key=len)

The output will be:

['Bob', 'Dan', 'Alice', 'Charlie']

In this case, the list is sorted based on the length of each name, from shortest to longest.

Ordering Values With .sort()

In addition to using the sorted() function, Python provides an alternative method for sorting lists directly. The .sort() method is called on the list itself and modifies the list in place:

numbers = [6, 9, 3, 1]

After calling .sort(), the original list is sorted:

[1, 3, 6, 9]

Unlike sorted(), .sort() does not return a new sorted list. Instead, it modifies the original list directly. Therefore, there is no need to assign the output of .sort() to a new variable. In this case, the numbers list will be sorted and no further action is needed.

When to Use sorted() and When to Use .sort()

When deciding whether to use sorted() or .sort(), consider the following:

  • Use sorted() when you want to sort a list without modifying the original list. This is useful when you want to keep the original order intact and have a sorted version available for later use.
  • Use .sort() when you want to sort a list in place, modifying the original list. This is useful when you do not need to preserve the original order and want to make changes directly to the list.

How to Sort in Python: Conclusion

In this tutorial, you learned how to use the sorted() function and the .sort() method in Python. You can use these tools to sort different types of data in different data structures, customize the sort order, and choose between modifying the original list or creating a new sorted list. Sorting is an essential operation for many programming tasks, and Python provides robust functionality to handle various sorting requirements.