Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
How to Compute the Cartesian Product of Two Lists in Python
Generates all ordered pairs from two lists using itertools.product and prints each combination.
from itertools import product
# Two small input lists
list_a = [1, 2, 3]
list_b = ["x", "y"]
# Compute the Cartesian product
result = list(product(list_a, list_b))
# Display the result
print("Cartesian product of", list_a, "and", list_b, "is:")
for pair in result:
print(pair)
How to Generate Permutations of Length r in Python
Generate and print all r-length permutations of a list using Python's itertools.permutations.
from itertools import permutations
def show_permutations(items, r):
result = list(permutations(items, r))
for perm in result:
print(perm)
print(f"Total: {len(result)}")
if __name__ == "__main__":
data = ["A", "B", "C"]
show_permutations(data, 2)
How to Get All Combinations of a List in Python
Generate and display all combinations of a given length from a list using Python's itertools.combinations.
from itertools import combinations
def list_combinations(items, r):
"""Return all combinations of length r from a list."""
return list(combinations(items, r))
if __name__ == "__main__":
fruits = ["apple", "banana", "cherry", "date"]
pick = 2
result = list_combinations(fruits, pick)
print…
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.