Fundamentals 4 min read
Python collections, heapq, bisect, and array modules: examples and usage
This article introduces Python's collections, heapq, bisect, and array standard‑library modules, explaining their purpose and providing clear code examples for namedtuple, deque, heap operations, binary search, and efficient array handling in everyday programming.
Test Development Learning Exchange
Test Development Learning Exchange
collections module provides supplementary container data types such as namedtuple and deque .
from collections import namedtuple
# Define a coordinate point
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, 22)
print("Point coordinates:", p.x, p.y) from collections import deque
# Create a double‑ended queue with a maximum length of 3
dq = deque(maxlen=3)
dq.append(1)
dq.append(2)
dq.append(3)
dq.append(4)
print("Deque after appending 4:", dq)
dq.appendleft(5)
print("Deque after appending 5 to the left:", dq)heapq module implements heap queue algorithms for building min‑heaps or max‑heaps.
import heapq
# Build a min‑heap
heap = []
elements = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
for element in elements:
heapq.heappush(heap, element)
print("Heap:", heap) import heapq
# Pop the smallest element
print("Smallest element:", heapq.heappop(heap)) import heapq
# Build a max‑heap using negative values
max_heap = [-element for element in elements]
for element in max_heap:
heapq.heappush(heap, element)
print("Max Heap:", [-element for element in heap])bisect module offers functions for binary searching in sorted lists.
import bisect
# Find the position of an element in a sorted list
sorted_list = [1, 2, 4, 4, 8]
index = bisect.bisect_left(sorted_list, 4)
print("Index of 4:", index) import bisect
# Insert an element while maintaining order
bisect.insort_left(sorted_list, 6)
print("List after inserting 6:", sorted_list)array module provides compact array types that are more memory‑efficient than Python lists.
import array
# Create an integer array
arr = array.array('i', [1, 2, 3])
print("Array:", arr) import array
# Modify the array by appending a value
arr.append(4)
print("Array after appending 4:", arr) import array
# Slice the array
slice_arr = arr[1:3]
print("Sliced array:", slice_arr)Written by
Test Development Learning Exchange
Test Development Learning Exchange
0 followers
Reader feedback
How this landed with the community
Rate this article
Was this worth your time?
Discussion
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.