Sorting in Python

Sorting in Python

Sorting in Python is a vital task.

For example, let’s create sorted versions of a list of numbers/list of strings:

numbers = [5, 3, 9, 2, 1, 3, 4]
names = ["Bob", "Charlie", "David", "Alice"]

# Sort in increasing order:
inc_nums = sorted(numbers)

# Sort in decreasing order:
dec_nums = sorted(numbers, reverse=True)

# Sort alphabetically
alpha_names = sorted(names)

# Sort in reversed alphabetic order:
rev_alpha_names = sorted(names, reverse=True)

In this guide, you find common examples on how to sort lists and dictionaries in Python.

Sorting a List in Python

There are two ways to sort a list in Python:

  1. Sort a list directly by calling sort() method of a list.
  2. Create a sorted copy of a list by calling sorted() function on a list.

How to Sort a List of Strings in Python

There are two common tasks related to sorting a list of strings:

  1. How to sort a list of strings alphabetically.
  2. How to sort a list of string in reversed alphabetic order.

Here is an example of how to sort a list of strings in alphabetic order:

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

sorted_names = sorted(names)

And here is an example of how to sort a list of strings in a reversed alphabetic order:

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

reverse_names = sorted(names, reverse=True)

How to Sort a List of Numbers in Python

To sort a list of numbers in increasing order:

numbers = [5, 3, 9, 2, 1, 3, 4]

increasing_nums = sorted(numbers)

To sort a list of numbers in decreasing order, call sorted() and set reverse to True.

numbers = [5, 3, 9, 2, 1, 3, 4]

decreasing_nums = sorted(numbers, reverse=True)

How to Sort a List of Python Objects

To sort a list of objects, decide the criteria based on which the sort will take place.

For instance, let’s create a class Fruit:

class Fruit:
    def __init__(self, weight, name):
        self.weight = weight
        self.name = name

Next, let’s create a list of fruits:

banana = Fruit(1, "Banana")
orange = Fruit(0.25, "Orange")
apple = Fruit(0.5, "Apple")

fruits = [banana, apple, orange]

Let’s sort this list of fruits by weight. To do this, you need to specify the key for the sort method, which acts as a sorting criterion.

fruits.sort(key=lambda fruit: fruit.weight)

Now you can make sure that the result is what you expected:

for fruit in fruits:
    print(fruit.name, fruit.weight)

Output:

Orange 0.25
Apple 0.5
Banana 1

How to Sort a List of Dates in Python

To sort a list of dates, call the sort() method on a list of dates.

For example:

import datetime

dates = [datetime.date(2021, 1, 3), datetime.date(2021, 1, 1), datetime.date(2021, 1, 2)]

dates.sort()

print(dates)

Output:

[datetime.date(2021, 1, 1), datetime.date(2021, 1, 2), datetime.date(2021, 1, 3)]

How to Sort a List of Tuples in Python

To sort a list of tuples:

  • Decide the index of the tuple you want to use as a sorting criterion.
  • Call sorted() on the list of tuples.

For example:

# (x, y) coordinate pairs
locations = [
    (0, 2),
    (5, 1),
    (3, 9),
    (1, 6)
]

# Sort locations based on the y coordinate.
sorted_locations = sorted(locations, key=lambda location: location[1])

print(sorted_locations)

Output:

[(5, 1), (0, 2), (1, 6), (3, 9)]

How to Sort a List of Dictionaries in Python

To sort a list of dictionaries:

  • Decide the list sorting criterion. For example, sort the list by dictionary keys.
  • Call sorted() on the list of dictionaries.

For example, let’s sort a dictionary of students by student name:

students = {
    "Alice": "Physics",
    "Charlie": "Chemistry",
    "Bob": "Maths"
}

sorted_students = sorted(students, key=lambda student: student[0])

print(sorted_students)

Output:

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

Sorting a Dictionary in Python

In Python versions earlier than 3.7 it is not possible to sort a dictionary. This is because a dictionary is an unordered collection. This makes sorting a meaningless operation.

However, as of Python 3.7 it has been possible to sort dictionaries. To do this, you can use the sorted() function.

How to Sort a Dictionary by Key

To sort a dictionary by key (in Python 3.7+):

  • Grab the dictionary entries by calling items() method on it.
  • Sort the items by calling sorted().
  • Convert the sorted items back to a dictionary.

Here is an example of sorting a dictionary by keys (names of the students):

data = {"Bob": 12, "Charlie": 5, "Alice": 9, "David": 82}
sorted_data = dict(sorted(data.items()))

print(sorted_data)

Output:

{'Alice': 9, 'Bob': 12, 'Charlie': 5, 'David': 82}

How to Sort a Dictionary by Value

To sort a dictionary by value (in Python 3.7+):

  • Grab the dictionary entries by calling items() method on it.
  • Sort the items by calling sorted() and specify the sorting criterion.
  • Convert the sorted items back to a dictionary.

Here is an example of sorting a dictionary by values (ages of the students):

data = {"Alice": 23, "Bob": 21, "Charlie": 32, "David": 29}
sorted_data = dict(sorted(data.items(), key=lambda item: item[1]))

print(sorted_data)

Output:

{'Bob': 21, 'Alice': 23, 'David': 29, 'Charlie': 32}

How to Sort a Set

You cannot sort a set in Python.

A Python set is an unordered and unindexed collection of elements. Thus, sorting a set is not an option.

Notice, however, that printing a set prints the set in an ordered manner.

For instance:

num_set = {3, 5, 2, 1, 10, 4}
print(num_set)

Output:

{1, 2, 3, 4, 5, 10}

If you for some reason call sorted() function on a set, it will convert the set into a list.

How to Sort a Tuple

A tuple is an immutable collection of elements. This means you cannot modify a tuple.

In other words, you cannot sort a tuple—directly.

But you can call the sorted() function on a tuple. This creates a list with the sorted values of the tuple.

To convert this list back to a tuple, call the tuple() function on it.

numbers = (7, 5, 2, 1, 3, 2, 10)
numbers = tuple(sorted(numbers))

print(numbers)

Output:

(1, 2, 2, 3, 5, 7, 10)

However, if you find yourself sorting tuples, you need to re-think about using tuples in the first place. This is because a tuple is not meant to be changed. If you want to sort a tuple, use a list instead.

Conclusion

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading

Python Interview Questions and Answers

Useful Advanced Features of Python

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published.