Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
How to Compute the Dot Product of Two Lists in Python
Compute the dot product of two equal-length numeric lists using a generator expression with zip and sum.
def dot_product(list1, list2):
"""
Compute the dot product of two numeric lists.
The lists must have the same length.
"""
if len(list1) != len(list2):
raise ValueError("Lists must have the same length")
return sum(a * b for a, b in zip(list1, list2))
if __name__ == "__main__":
…
How to Evaluate RPN Expressions in Python
Use a stack to evaluate Reverse Polish Notation token lists with a dictionary of operator lambdas, truncating division toward zero.
def eval_rpn(tokens):
stack = []
ops = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: int(a / b) # truncate toward zero
}
for token in tokens:
if token in ops:
b = stack.pop()
a = stack.pop(…
Browse by section
Each section groups closely related Python snippets.
Algorithms & data structures — Python code examples
What you will find here
This page collects algorithms & data structures snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.