Modern Python Standard Library Cookbook

Modern Python Standard Library Cookbook

Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
21
Index

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:

  1. Take the following set of elements:
>>> values = [ 5, 3, 1, 7 ]
  1. Looking up an element in the sequence can be done through the in operator:
>>> 5 in values
True
  1. Sorting can be done through the sorted function:
>>> sorted_value = sorted(values...
Unlock full access

Continue reading with a subscription

Packt gives you instant online access to a library of over 7,500 practical eBooks and videos, constantly updated with the latest in tech

End of Section 3

Your notes and bookmarks