Collection Patterns

Python CollectionsFree Lesson

Advertisement

Collection Patterns

Custom collections, iterators, and advanced data structures.

Overview

Master collection patterns.

Custom Collection

class PriorityQueue:
    def __init__(self):
        self._queue = []
        self._index = 0
    
    def push(self, item, priority):
        heapq.heappush(self._queue, (-priority, self._index, item))
        self._index += 1
    
    def pop(self):
        return heapq.heappop(self._queue)[-1]

import heapq
pq = PriorityQueue()
pq.push("low", 1)
pq.push("high", 10)
pq.push("medium", 5)

print(pq.pop())  # high
print(pq.pop())  # medium

Iterator Pattern

class Range:
    def __init__(self, start, stop=None, step=1):
        if stop is None:
            start, stop = 0, start
        self.start = start
        self.stop = stop
        self.step = step
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.step > 0 and self.start >= self.stop:
            raise StopIteration
        if self.step < 0 and self.start <= self.stop:
            raise StopIteration
        
        value = self.start
        self.start += self.step
        return value

for i in Range(10):
    print(i, end=" ")

Practice

Implement a custom sorted list with O(log n) insertion.

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement