Better Programming

Advice for programmers.

Follow publication

Member-only story

Python Collections Module: Essential Tools for Efficient Coding

Harnessing the power of namedtuple, deque, ChainMap, Counter, OrderedDict, and defaultdict

Benedict Neo
Better Programming
Published in
8 min readJan 26, 2023

--

made with stable diffusion

Python’s collections module is a powerful tool that developers often overlook. It offers a variety of utilities that can help you write more concise and efficient code by reducing boilerplate and providing abstractions for common operations

In this article, we will explore six of the most useful data types from the collections module:

  • namedtuple() — factory function for creating tuple subclasses with named fields
  • deque — list-like container with fast appends and pops on either end
  • 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 were added
  • defaultdict — dict subclass that calls a factory function to supply missing values

We’ll touch on each of them, providing a practical example with code, and then give examples of how they are used in the real world.

Let’s dive right in.

The code is on Deepnote.

namedtuple()

A practical use case for namedtuple could be creating an account with the following information: name, balance, and currency.

from collections import namedtuple

# Define a namedtuple for representing a bank account
Account = namedtuple('Account', ['name', 'balance', 'currency'])

# Create an account
my_acc = Account(name='John Doe', balance=100.0, currency='USD')

# __repr__
print(my_acc) # Output: Account(name='John Doe', balance=100.0, currency='USD')

# Access the fields of the account using dot notation
print(my_acc.name) # Output: 'John Doe'
print(my_acc.balance) # Output: 100.0…

--

--

No responses yet

Write a response