Python Sorting

In Python, you can sort a list using the sort() method or the sorted() function.

A simple use of sort is the sorted(list) function.

a = [5, 1, 4, 3, 2]
print(a)            ## [5, 1, 4, 3, 2]
print(sorted(a))    ## [1, 2, 3, 4, 5]

You can add other arguements such as reverse which puts the list backwards.

b = [9, 6, 8, 5, 7]
print(b)                         ## [9, 6, 8, 5, 7]
print(sorted(b, reverse=True))   ## [9, 8, 7, 6 ,5]

Custom Sorting with key=

This allows you to evaluate the element and sort based upon the result.

values = ['ccc', 'aaaa', 'd', 'bb']
print(sorted(values, key=len))      ## ['d', 'bb', 'ccc', 'aaaa']

You can also call a function as a key value

values = ['xc', 'zb', 'yd', 'wa']

# This function `my_fn`returns the last character from the string using the `-1`
def my_fn(s):
    return s[-1]

# The function is called by the key and the results are evalauted based on the last character in the string
print(sorted(values, key=my_fn))    ## ['wa', 'zb', 'xc', 'yd']

Tuples

A tuple is an ordered collection of elements, which can be of any type, and is defined using parentheses () or without any brackets. A tuple is similar to a list, but it is immutable, which means that once it is created, its elements cannot be modified.

my_tuple = (1, 2, 3, "four", 5.0)

List comprehensions

A list comprehension is a concise and readable way to create a new list by applying an expression to each element of an existing list (or other iterable), subject to a conditional test. The basic syntax of a list comprehension is as follows:

new_list = [expression for item in iterable if condition]

An example of a list comprehension that creates a new list of the squares of the numbers from 1 to 5

squares = [x**2 for x in range(1, 6)]

In this example, we use the range() function to create an iterable that generates the numbers from 1 to 5. We then use a list comprehension to create a new list squares that contains the squares of each number in the iterable. The expression x**2 is applied to each number in the iterable, and the resulting value is added to the new list squares.

Result

[1, 4, 9, 16, 25]
Last modified July 21, 2024: update (e2ae86c)