Sorting data in a specific order is an important task in any programming language. For instance, you might need to display a list of items sorted in ascending order by price or you may need to sort records of customers by purchase date.

Python is blessed with a couple nice sorting methods so you don’t have to write your own sorting algorithms, like bubble sort or Quicksort. We’re going to show you how to sort items in a Python collection using the sort() and sorted() methods. The sort() method sorts a collection in-place (without creating a new copy), while the sorted() method doesn’t modify the original collection. Instead, it creates a copy that contains your sorted items.

Sorting In-place via Sort Method

Let’s first see some examples of in-place sorting using the sort() method.

Sorting Alphabetically

To sort items in alphabetical order, you need to call the sort() method using the collection object, like a list. Here’s an example. This script creates a list of strings that correspond to some dummy names. The list is then printed on the console. Next, the sort() method is called on the names list which sorts the list in-place. Finally the sorted list is again printed on the console.

names = ["John", "Sally", "Elizabeth", "Nick", "Rose"]

print("Before Sorting:")
print(names)

names.sort()

print("After Sorting:")
print(names)

The output shows that the names list has been sorted alphabetically.

Output:

Before Sorting:
['John', 'Sally', 'Elizabeth', 'Nick', 'Rose']
After Sorting:
['Elizabeth', 'John', 'Nick', 'Rose', 'Sally']

To sort a list in the reverse alphabetical order, you need to pass True as a value for the reverse parameter of the sort() function. The following script sorts the names list in the reverse alphabetical order.

names.sort(reverse= True)

print("After Sorting:")
print(names)

Output:

After Sorting:
['Sally', 'Rose', 'Nick', 'John', 'Elizabeth']

Sorting Numerically

To sort a list numerically, you can again use the sort() method which sorts the list in ascending order.

ages = [25, 30, 21, 19, 27]

print("Before Sorting:")
print(ages )

ages .sort()

print("After Sorting:")
print(ages)

Output:

Before Sorting:
[25, 30, 21, 19, 27]
After Sorting:
[19, 21, 25, 27, 30]

In order to sort a numeric list in descending order, you need to pass True as a value to the reverse parameter. Here’s an example:

ages.sort(reverse= True)

print("After Sorting:")
print(ages)

Output:

After Sorting:
[30, 27, 25, 21, 19]

Sorting Using Keys

If you have a list of collections with multiple values, you can use the key parameter of the sort() method to specify the value you want to use when sorting the data. Keys can be a bit confusing sp this is best explained with a fresh example.

The following script creates a list of student information. The list contains 5 tuples. We assume that each tuple stores information, like their name, age, marital status, and a balance of how much tuition is owed.

students = [
           ("John", 25, True, 10500),
           ("Sally", 30, True, 7900),
           ("Elizabeth", 21, False, 7250),
           ("Nick", 19, False,8520),
           ("Rose", 27, True, 2600)
            ]

The sort() method can be used to sort the tuples in the students based on one of the attributes i.e. name, age, married, and amount. To do so, you first have to create a lambda function which accepts a list and returns the key at nth index. Next, you need to pass the lambda function to the key parameter of the sort() method.

The following script sorts the tuples in the students list based on the 0th index of each tuple item. We assume that the 0th index contains student names. Therefore, in the output you’ll see that the tuples in the students list are sorted based on the alphabetical order of student names.

name = lambda student:student[0]
students.sort(key = name)
print(students)

Output:

[('Elizabeth', 21, False, 7250), ('John', 25, True, 10500), ('Nick', 19, False, 8520), ('Rose', 27, True, 2600), ('Sally', 30, True, 7900)]

Similarly, if you want to sort the tuples in the students list based on the descending order of the amount that each student owes, you select the 3rd index in your lambda function. Note that the index numbers in a tuple start from 0 so the 3rd index corresponds to the 4th item in a tuple.

amount = lambda student:student[3]
students.sort(key = amount, reverse = True)
print(students)

In the output, you can see that the tuples in the students list are now sorted in descending order of the 4th item in the tuples.

Output:

[('John', 25, True, 10500), ('Nick', 19, False, 8520), ('Sally', 30, True, 7900), ('Elizabeth', 21, False, 7250), ('Rose', 27, True, 2600)]

Want to do more with Python?

We've uncovered a lot more tricks to help you get the most out of Python. To take your Python programming to the next level, enter your email address below and we'll send you our most powerful Python tricks yet.

Yes, show me more free Python tips

Creating Sorted Copies via Sorted Method

The sort() function sorts a list in-place so your original list order is altered. If you don’t want to change the original list, you can use the sorted() method to create a new list with your sorted items. You simply need to pass the original list as a parameter value to the sorted() method.

Let’s first see what happens when you call the sort() method on a list and try storing the result in another variable.

names = ["John", "Sally", "Elizabeth", "Nick", "Rose"]
sorted_names = names.sort()
print(sorted_names)

The output below shows none because the names list in the above script is sorted in-place and the sort() method returned null which is the displayed on the console.

Output:

None

Even though you wanted to store the sorted list to a new variable, what you actually did was sort the names list, permanently overwriting the order in your original list. This isn’t what we wanted to do so let’s try a different method. You can create a new list containing sorted items from the original list using the sorted() method.

names = ["John", "Sally", "Elizabeth", "Nick", "Rose"]
sorted_names = sorted(names)

print(names)
print(sorted_names)

The output shows the original names list remains unsorted, while our new list, returned by the sorted() method, is now sorted.

Output:

['John', 'Sally', 'Elizabeth', 'Nick', 'Rose']
['Elizabeth', 'John', 'Nick', 'Rose', 'Sally']

Like the sort() method, you can sort the items in reverse order by passing True as the parameter value for the reverse parameter of the sorted() function, like this:

sorted_names = sorted(names, reverse = True)
print(sorted_names)

Output:

['Sally', 'Rose', 'Nick', 'John', 'Elizabeth']

Sorting items in a tuple

This is where things get interesting. The need for the sorted() method becomes evident when trying to sort a tuple. The sort() method simply cannot sort items in a tuple since tuples are immutable. Because they’re immutable, it’s impossible to sort them in-place. Let’s see what happens when you try to sort items in a tuple via the sort() method.

names = ("John", "Sally", "Elizabeth", "Nick", "Rose")
names.sort()
print(names)

You’ll get an exception like this since tuples are immutable.

Output:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-12-bc5b649692b5> in <module>
      1 names = ("John", "Sally", "Elizabeth", "Nick", "Rose")
----> 2 names.sort()
      3 print(names)

AttributeError: 'tuple' object has no attribute 'sort'

Let’s now try to sort a tuple using the sorted() method. The sorted method creates a new list that contains items from the original tuple but in a sorted order.

names = ("John", "Sally", "Elizabeth", "Nick", "Rose")
sorted_names = sorted(names)

print(names)
print(sorted_names)

The output below shows the original tuple and the new list which contains sorted items from the original tuple.

Output:

('John', 'Sally', 'Elizabeth', 'Nick', 'Rose')
['Elizabeth', 'John', 'Nick', 'Rose', 'Sally']

The square brackets confirm the sorted tuple is now stored as a list, rather than a tuple - but at least it’s sorted!

Finally, just like the sort() method, you can also use the sorted() method to sort based on keys in a collection of items. The only difference between the sort() method and the sorted() method is that the first parameter to the sorted() method is the collection you want to sort. The key and reverse parameters remain the same for the two methods.

Our next script uses the sorted() method to create a students_sorted list which contains items from the students list sorted by the 4th item of the tuples. The output prints both our original list and the new sorted list.

students = [
           ("John", 25, True, 10500),
           ("Sally", 30, True, 7900),
           ("Elizabeth", 21, False, 7250),
           ("Nick", 19, False,8520),
           ("Rose", 27, True, 2600)
            ]


amount = lambda student:student[3]
students_sorted = sorted(students, key = amount, reverse = True)

print(students)
print(students_sorted)

Output:

[('John', 25, True, 10500), ('Sally', 30, True, 7900), ('Elizabeth', 21, False, 7250), ('Nick', 19, False, 8520), ('Rose', 27, True, 2600)]
[('John', 25, True, 10500), ('Nick', 19, False, 8520), ('Sally', 30, True, 7900), ('Elizabeth', 21, False, 7250), ('Rose', 27, True, 2600)]

Want to do more with Python?

We've uncovered a lot more tricks to help you get the most out of Python. To take your Python programming to the next level, enter your email address below and we'll send you our most powerful Python tricks yet.

Yes, show me more free Python tips