Skip to content

Data structures

Lists

Dicts

Stacks

  • list
    • amortized O(1) for inserts and deletes

collections.deque

  • double-ended queue
    • linked list

Adding: stack is the same as queue

>>> from collections import deque
>>> s = deque()
>>> s.append('eat')

>>> s.pop()
'eat'
>>> s.pop()
IndexError: "pop from an empty deque"

queue.LifoQueue

  • multi-producers & multi-consumers from different threads
    • same process
>>> from queue import LifoQueue
>>> s = LifoQueue()
>>> s.put('eat')
>>> s.get()
'eat'
>>> s.get_nowait()
queue.Empty
>>> s.get()
# Blocks / waits forever...

Queues

collections.deque

Adding: stack is the same as queue

>>> from collections import deque
>>> q = deque()
>>> q.append('eat')
>>> q.popleft()
'eat'
>>> q.popleft()
IndexError: "pop from an empty deque"

queue.Queue

  • multi-producers & multi-consumers from different threads
    • same process
>>> from queue import Queue
>>> q = Queue()
>>> q.put('eat')
>>> q.get()
'eat'
>>> q.get_nowait()
queue.Empty
>>> q.get()
# Blocks / waits forever...

multiprocessing.Queue

  • similar to queue.Queue
  • also handles different processes vs threads

Priority Queue

heapq

  • binary heap
from heapq import heapq

pq = []

heappush(pq.(2, 'code'))

queue.PriorityQueue

  • wrapper around heapq
  • supports concurrency (locks, threads, ...)
  • API is class based
from queue import PriorityQueue

q = PriorityQueue()
q.put((2, 'code'))
q.put((1, 'eat'))
q.put((3, 'sleep'))

Dates

from datetime import datetime

>>> datetime.now()
datetime.datetime(2022, 8, 11, 19, 15, 16, 561797)

Time intervals

timedelta only has total_seconds()

from datetime import datetime, timedelta

t0 = datetime(year=2022, month=1, day=1)
t1 = datetime(year=2022, month=8, day=11)

diff = t1 - t0
>>> diff
datetime.timedelta(days=222)
>>> diff.total_seconds()
19180800.0

Time delta in days instead of seconds

days = diff / timedelta(days=1)

>>> days
222.0

Last update: 2022-09-23