Simplifying
To reduce the complexity of code, the way data is stored is fundamental. You should pick your data structure carefully. This section provides a few examples on how the performance of simple code snippets can be improved by the proper datatypes for the job.
Searching in a list
Due to 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 is not especially bad if you don't need to perform many element index lookups, but it can have a negative performance impact if there is a need for many such operations.
If you need fast search over a list, you can try the bisect ...
Get Expert Python Programming - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.