Searching, sorting, filtering
Searching for an element is a very common need in programming. Looking up an item in a container is basically the most frequent operation that your code will probably do, so it's very important that it's quick and reliable.
Sorting is frequently connected to searching, as it's often possible to involve smarter lookup solutions when you know your set is sorted, and sorting means continuously searching and moving items until they are in sorted order. So they frequently go together.
Python has built-in functions to sort containers of any type and look up items in them, even with functions that are able to leverage the sorted sequence.
How to do it...
For this recipe, the following steps are to be performed:
- Take the following set of elements:
>>> values = [ 5, 3, 1, 7 ]
- Looking up an element in the sequence can be done through the
in
operator:
>>> 5 in values
True
- Sorting can be done through the
sorted
function:
>>> sorted_value = sorted(values...