How to Sort a List in Python (with Examples)

# How to Sort a Python List

To sort a Python list, use the built-in `sort()` method.

For example:

```numbers = [3, 1, 2]

numbers.sort()

print(numbers)```

Output:

`[1, 2, 3]`

Or to reverse sort a list of numbers, you can do:

```numbers = [3, 1, 2]

numbers.sort(reverse=True)

print(numbers)```

These two are some basic usage of the `sort()` method in Python. But you can do a lot more with it too, such as:

• Sort a list by a custom criterion
• Reverse sort a list
• Create a new sorted version of a list
• Sort a list of tuples by the nth element

To learn how these and much more, let’s dive deeper into the world of sorting a list in Python.

## How to Sort Lists in Python

The `sort()` method in Python sorts a list “in-place”. This means it does not create a new list. Instead, it sorts the original one.

In the introduction, you saw a simple use case of the `sort()` method of a list.

However, it is important to notice that the full syntax for calling `sort()` is:

`list.sort(reverse, key)`

Where:

• `reverse` is an optional keyword argument. If you set it `True`, the sort happens in a reversed order
• `key` is also an optional keyword argument. You can assign it a function that acts as a sorting criteria. This function can be a built-in function or your own function.

To learn what this means in practice, let’s see some examples

### How to Reverse Sort a List in Python

To sort a list in reversed order, set the keyword argument `reverse` to `True`.

For example:

```numbers = [3, 1, 2]

numbers.sort(reverse=True)

print(numbers)```

Output:

`[3, 2, 1]`

### How to Sort a List of Strings by Length

To sort a list based on length, specify the `len` as a sorting function. This happens by specifying the `key` argument in the `sort()` call.

For example:

```fruits = ["Pineapple", "Cranberries", "Orange", "Pear"]

fruits.sort(key=len)

print(fruits)```

Output:

`['Pear', 'Orange', 'Pineapple', 'Cranberries']`

The `sort()` applies the `len` function on each string in the list. It then sorts the list based on the results.

Notice that you can also create a custom function and pass it into the `sort()` method. Let’s see how that works in the next section.

### How to Sort a List with a Custom Function in Python

You can sort a Python list with a custom criterion (sorting function).

To do this, you need to have a function and pass it as a `key` into the `sort() `method.

For example, let’s sort a list of numbers based on if they are even or odd. The order does not matter. All we care about is that the odd numbers are first.

• To do this, create a function that checks if a number is even or odd.
• Then pass this function into the `sort()` method call as the `key`.

Let’s see how this looks like in code:

```def is_even(num):
return num % 2 == 0

nums = [19, 2, 4, 71, 2, 6, 1, 2, 2003, 7]

nums.sort(key=is_even)

print(nums)```

Output:

`[19, 71, 1, 2003, 7, 2, 4, 2, 6, 2]`

Notice how the numbers are not in increasing nor decreasing order. The `sort()` method sorted the list such that the odd numbers come first. It did it by running the function `is_even` for each element in the list and comparing the results.

Now you know how to make a function act as a sorting criterion.

Let me then show you how you can make the above example a bit shorter using a lambda expression.

### How to Sort a List with a Lambda Expression in Python

It may be clumsy to create a separate function for the `sort()` method that is used only once.

To overcome this inconvenience, you can define the function directly into the `sort()` call. To do this, however, you cannot use a regular function. Instead, you need to use a lambda function.

In short, a lambda function is a regular function that has no name. It is meant to be used when the functionality is needed only once.

Let’s repeat the previous example where we sort a list of numbers by whether they are odd or even. This time, let’s use a lambda function as a sorting function. This lambda function checks if a number is odd or even.

Here is the code:

```nums = [19, 2, 4, 71, 2, 6, 1, 2, 2003, 7]

nums.sort(key=lambda number: number % 2 == 0)

print(nums)```

Output:

`[19, 71, 1, 2003, 7, 2, 4, 2, 6, 2]`

As you can see, the result is the same as in the previous example. But the solution is more elegant. It is easy to read. No extra functions are needed.

Now you understand the basics of sorting in Python.

Next, let’s have a look at how you can indirectly sort a list by creating a sorted copy of the list.

## How to Sort a List by Creating a New One

If you don’t want to directly sort a list, use the `sorted()` function. It returns a new list with the sorted elements.

The `sorted()` function works the same way as the built-in `sort()` method of a list. The difference is that `sorted()` is not a method of a list. It is a built-in function of Python. You can call it on a list or any other iterable.

The syntax:

`sorted(iterable, reverse, key)`

Where:

• `iterable` is the sequence to be sorted. For example, it can be a list.
• `reverse` is an optional keyword argument. If you set it `True`, the sort happens in a reversed order.
• `key` is also an optional keyword argument. You can assign it a function that acts as a sorting criteria.

Because you already know how the `sort()` method works, we don’t need to go through the theory all over again.

Let’s see two examples right away.

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

```numbers = [3, 1, 2]

sorted_nums = sorted(numbers)

print(sorted_nums)```

Output:

`[1, 2, 3]`

And let’s also see a more advanced example where we sort a list of strings by length:

```fruits = ["Pineapple", "Cranberries", "Orange", "Pear"]

sorted_fruits = sorted(fruits, key=len)

print(sorted_fruits)```

The result is a new list with sorted fruits based on the length of the name:

`['Pear', 'Orange', 'Pineapple', 'Cranberries']`

That’s it for the theory of sorting lists in Python.

Last but not least, let’s see common examples of sorting lists in Python.

## How to Sort a List of Strings Alphabetically

To sort a list of strings alphabetically, call `sort()` method on it. This works because the `sort()` method sorts alphabetically by default.

For instance:

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

names.sort()

print(names)```

Output:

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

## How to Sort a List of Strings in a Reversed Alphabetic Order

To sort a list of strings in a reversed alphabetic order, pass the `reverse=True` into the `sort()` call.

For example

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

names.sort(reverse=True)

print(names)```

Output:

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

## How to Sort a List of Numbers in Ascending Order

To sort a list of strings in ascending (increasing) order, call `sort()` on a list of numbers.

The `sort()` method sorts the list in increasing order by default.

For example:

```numbers = [3, 1, 2]

numbers.sort()

print(numbers)```

Output:

`[1, 2, 3]`

## How to Sort a List of Numbers in Descending Order

To sort a list of numbers in a descending (decreasing) order, use the `sort()` method and set `reverse=True`.

For instance:

```numbers = [3, 1, 2]

numbers.sort(reverse=True)

print(numbers)```

Output:

`[3, 2, 1]`

## How to Sort a List of Tuples

To sort a list of tuples, you need to specify by which `tuple` element to sort.

For example, let’s sort a list of `(x, y)` coordinate pairs by the x value. In other words, the sort happens by the value corresponding to the index `0` in the tuple:

```coords = [(1, 200), (10, 1), (3, 2), (4, 0)]

coords.sort(key=lambda pair: pair)

print(coords)```

Output:

`[(1, 200), (3, 2), (4, 0), (10, 1)]`

To sort by y-value, just change the index at the lambda expression.

```coords = [(1, 200), (10, 1), (3, 2), (4, 0)]

coords.sort(key=lambda pair: pair)

print(coords)```

Output:

`[(4, 0), (10, 1), (3, 2), (1, 200)]`

Bonus: To sort a list of coordinates by their distance to the origin:

```import math

coords = [(1, 200), (10, 1), (3, 2), (4, 0)]

# Calculate the distance to the origin by pythagorean theorem:
coords.sort(key=lambda pair: math.sqrt((pair - 0) ** 2 + (pair - 0) ** 2))

print(coords)```

Output:

`[(3, 2), (4, 0), (10, 1), (1, 200)]`

## How to Sort a List of Objects

To sort a list of objects you need to utilize the `key` argument in the `sort()` method call. This is because you need to specify the sorting criterion.

For example, let’s create a `Fruit` class and a bunch of `Fruit` objects in a list. Let’s then sort the fruits by their mass.

To do this, we need to obtain the mass of `Fruit` object. To do this, let’s implement a `get_mass` method into the `Fruit` class. Then we can use this method as the sorting criterion.

Here is how it looks in code:

```class Fruit:
def __init__(self, type, mass):
self.type = type
self.mass = mass

def get_mass(self):
return self.mass

banana = Fruit("Banana", 0.5)
pineapple = Fruit("Pineapple", 1.5)
orange = Fruit("Apple", 0.3)

fruits = [banana, pineapple, orange]

fruits.sort(key=Fruit.get_mass)

for fruit in fruits:
print(fruit.type)```

Output:

```Apple
Banana
Pineapple```

## Conclusion

To sort a list in Python, use:

• `sort()` method to directly sort the original list.
• `sorted()` function to create a new list with sorted elements.

By default, both of these methods sort a list of numbers in increasing order, and a list of strings in alphabetical order.

Both methods also accept two optional keyword arguments:

• `reverse`. To sort in a reversed order, set this keyword argument true.
• `key`. A sorting criterion. This can be a reference to a regular function or a lambda expression.

Thanks for reading. Hope you enjoy it.

Happy coding! 