9) Idiomatic Data Structures Lesson

Python Collections Library

3 min to complete · By Martin Breuss

Additionally to the built-in data types that you've worked with extensively by now, Python also comes pre-packaged with a many additional data structures in the standard library. That means that they are only one import statement away!

Data Structures in Python Collections

One of these libraries is called collections and it provides specialized container data types:

  • deque: list-like container with fast appends and pops on either end
  • namedtuple(): factory function for creating tuple subclasses with named fields
  • ChainMap: dict-like class for creating a single view of multiple mappings
  • Counter: dict subclass for counting hashable objects
  • OrderedDict: dict subclass that remembers the order entries that were added
  • defaultdict: dict subclass that calls a factory function to supply missing values
  • UserDict: wrapper around dictionary objects for easier dict subclassing
  • UserList: wrapper around list objects for easier list subclassing
  • UserString: wrapper around string objects for easier string subclassing

A specialized container is just what you need for a better implementation of a stack and a queue data structure, and you'll use one of these classes in the next lesson to do just that.

Can you figure out which of them might be a good candidate from reading the short descriptions taken from the Python documentation?

Summary: Types of Python Collections

  • The collections module comes with several specialized container data types
  • These specialized containers offer better implementations of a Stack and Queue

Specialized Container Data Types in Collections

  • deque
  • namedtuple()
  • ChainMap
  • Counter
  • OrderedDict
  • defaultdict
  • UserDict
  • UserList
  • UserString