Reducing complexity by choosing appropriate data structures
To reduce code complexity, it's important to consider how data is stored. You should pick your data structure carefully. The following section will provide you with a few examples of how the performance of simple code snippets can be improved by the correct data types.
Searching in a list
Due to the implementation details of the
list type in Python, searching for a specific value in a
list isn't a cheap operation. The complexity of the
list.index() method is O(n), where n is the number of list elements. Such linear complexity won't be an issue if you only need to perform a few element index lookups, but it can have a negative performance impact in some critical code sections, especially if done over very large lists.
If you need to search through a
list quickly and often, you can try the
bisect module from Python's standard library. The functions in this module are mainly designed for inserting...