Sitemap
Balakrishna Maduru

Balakrishna Maduru

I specialize in developing analytics platforms that integrate open-source tools with both cloud and bare-metal environments for secure, scalable data management

Member-only story

Deque, ChainMap, and Counter from the Collections Module

3 min readNov 23, 2024
Press enter or click to view image in full size
Photo by Mark Fletcher-Brown on Unsplash

The Python collections module is a treasure trove of specialized data structures designed for specific use cases, offering functionality and memory efficiency beyond standard containers like list, dict, or set. Three standout tools — Deque, ChainMap, and Counter — address unique problems elegantly. Let’s dive into each, with examples and outputs to highlight their power.

1. Deque: The Double-Ended Queue

A deque (pronounced deck) is a list-like container optimized for fast appends and pops from both ends. Whether you’re building a queue, stack, or implementing sliding windows, deques outperform regular lists due to their efficient memory management.

Key Features

• Fast O(1) appends and pops from either end.

• Thread-safe operations.

• Optional maximum length for automatic size control.

Example: Sliding Window

from collections import deque

# Create a deque and manipulate it
dq = deque([1, 2, 3])
print("Initial deque:", dq)

# Append elements
dq.append(4)
dq.appendleft(0)
print("After appends:", dq)

# Pop elements
dq.pop()
dq.popleft()
print("After pops:", dq)

# Output :
# Initial deque: deque([1, 2, 3])
# After appends: deque([0, 1, 2, 3, 4])
# After pops: deque([1, 2…

--

--

Balakrishna Maduru
Balakrishna Maduru

Written by Balakrishna Maduru

I specialize in developing analytics platforms that integrate open-source tools with both cloud and bare-metal environments for secure, scalable data management