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.
You can add other arguements such as reverse which puts the list backwards.
Custom Sorting with key=
¶
This allows you to evaluate the element and sort based upon the result.
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.
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:
An example of a list comprehension that creates a new list of the squares of the numbers from 1 to 5
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