Using collections

The collections module provides high-performance alternatives to the built-in container types. The main types available in this module are:

  • deque: A list-like type with extra features
  • defaultdict: A dict-like type with a built-in default factory feature
  • namedtuple: A tuple-like type that assigns keys for members

deque

A deque is an alternative implementation for lists. While a list is based on arrays, a deque is based on a doubly linked list. Hence, a deque is much faster when you need to insert something into its middle or head but much slower when you need to access an arbitrary index.

Of course, thanks to the overallocation of an internal array in the Python list type, not every list.append() call requires memory reallocation, and ...

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.