collections, deque, heapq

List

  • List in Python is a Dynamic Array (Array list), string is a list of chars, and recursive (char is also str)

Bytes

  • Bytes, byte array - used to store values in range(0, 256), byte array is mutable array, bytes is immutable array

Tuple

collections.namedtuple → immutable class
typing.NamedTuple – Improved namedtuples with type annotations
  • types.SimpleNamespace - mutable namedtuple, you can access attributes with dot ‘.’

Dictionaries

Maps, and hash tables, associative arrays = O(1) time complexity for lookup, insert, update, and delete operations

collections.defaultdict
collections.ChainMap
  • collections.OrderedDict (for Python < 3.7)
types.MappingProxyType – A Wrapper for Making Read-Only Dictionaries
  • types.TypedDict - Similar to typing.NamedTuple but we access elements as dict[”key”]

Set, frozen-set → O(1) when checking membership

O(n) union, intersection, difference, subset operations

Counter

collections.Counter – Multi-sets, counts how many time element occurred

deque (queue, stack)

  • Stack - LIFO, Push / Pop (End of list)
    • list O(1)
    • collections.dequeappend, pop → O(1)
    • queue.LifoQueueput, get (for multiprocessing)
  • Queue - FIFO, on queue we add to end, delete from start
    • list is bad cuz it will take O(n) for pop(0)
    • collections.dequeappend, popleft → O(1)
    • queue.Queue → put, get
    • multiprocessing.Queue – Shared Job Queues (cuz of GIL)
  • Complexity table
    1. image
    2. Index access of deque is O(N). WHY? Unlike Python's standard list (which uses a single contiguous block of memory and supports true O(1) random access), collections.deque is implemented as a doubly-linked list of blocks (fixed-size memory chunks, typically 64 elements each)

heapq (priority queue, min heap by default)

  • Keeps list sorted with O(logN), we can use list, BUT it will take O(N*logN) because of insertion and sorting
queue.PriorityQueue - O(logN)
  • heap vs list
  • Operation
    Standard list
    heapq
    Access Minimum (heap[0])
    O(N) (un-sorted) O(1) (sorted)
    O(1)
    Insert New Element
    O(1) append()
    O(log N) heappush()
    Remove Minimum
    O(N) pop(0)
    O(log N) heappop()
    Random Index Access (arr[i])
    O(1)
    O(1) (Returns arbitrary tree node, not i-th smallest)
    Search by Value (x in arr)
    O(N)
    O(N)
    Full Sort
    O(N logN) sort()
    O(N log N) [heappop() for _ in range(N)]
  • What is the advantage of heap?
  • The primary advantage of a heap over a sorted list is efficiency when handling dynamic data.

    If you have a continuously changing collection of data where you constantly need to add new items and pull the smallest (or largest) item, a heap allows you to do both in O(log N) time—whereas keeping a list fully sorted costs O(N) time per insertion.

SuperMade with Super