As a rule of thumb, when optimizing pure Python code, you should look at what is available in the standard library. The standard library contains clever algorithms for the most common data structures such as lists, dicts, and sets. Furthermore, a lot of standard library modules are implemented in C and have fast processing times. However, it's important to always time the different solutions—the outcomes are often unpredictable.
collections module provides extra data containers that can efficiently handle some common operations. For example, you can use
deque in place of a list when you need to pop items from the start and append new items at the end. The
collections module also includes a