Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
Find Common Elements in List of Lists in Python
Return elements that appear in every sublist of a nested list, preserving duplicates with Counter intersection.
from collections import Counter
def common_elements(list_of_lists):
"""Return elements present in every sublist."""
if not list_of_lists:
return []
counts = Counter(list_of_lists[0])
for sublist in list_of_lists[1:]:
counts &= Counter(sublist)
return list(counts.elements())
if _…
Generate Pascal's Triangle Rows in Python
Builds Pascal's triangle as a list of rows, where each inner value is the sum of the two values above it.
def generate_pascals_triangle(rows):
triangle = []
for row_num in range(rows):
row = [1] * (row_num + 1)
for col in range(1, row_num):
row[col] = triangle[row_num - 1][col - 1] + triangle[row_num - 1][col]
triangle.append(row)
return triangle
if __name__ == "__main__":
…
How to Add Two Lists Elementwise in Python
Add two equal-length lists element by element using a list comprehension with zip, returning a new list of summed values.
def elementwise_add(list1, list2):
return [a + b for a, b in zip(list1, list2)]
if __name__ == "__main__":
list_a = [1, 2, 3, 4]
list_b = [10, 20, 30, 40]
result = elementwise_add(list_a, list_b)
print(result)
How to Compare Two Lists Elementwise for Greater Flags in Python
Compare two equal-length lists element by element and return a list of booleans marking where list_a values are greater than list_b values.
def compare_lists_greater(list_a, list_b):
"""
Compare two lists elementwise and return a list of booleans
indicating whether each element in list_a is greater than the
corresponding element in list_b.
"""
if len(list_a) != len(list_b):
raise ValueError("Lists must have the same length"…
How to Compute Jaccard Similarity in Python
Compute the Jaccard similarity between two lists by converting them to sets and dividing the intersection size by the union size.
def jaccard_similarity(list1, list2):
set1 = set(list1)
set2 = set(list2)
intersection = set1 & set2
union = set1 | set2
if not union:
return 0.0
return len(intersection) / len(union)
if __name__ == "__main__":
a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 6, 7]
pri…
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 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 Flatten List of Dict Values in Python
This code flattens the values of a list of dictionaries into a single list, handling both list values and scalar values.
def flatten_dict_values(dicts):
flattened = []
for d in dicts:
for value in d.values():
if isinstance(value, list):
flattened.extend(value)
else:
flattened.append(value)
return flattened
if __name__ == "__main__":
data = [
{"a": …
How to Split a List by a Predicate into Two Lists in Python
Partition any Python list into two lists based on a predicate: items that match go into one list, everything else into the other.
from typing import Callable, List, TypeVar
T = TypeVar("T")
def split_by_predicate(items: List[T], predicate: Callable[[T], bool]) -> tuple[List[T], List[T]]:
matching = []
non_matching = []
for item in items:
if predicate(item):
matching.append(item)
else:
non_mat…
Reorder a List by Odd Even Indices in Python
Splits a list into two sublists based on 1-based index parity, then concatenates odd-indexed elements before even-indexed ones.
def reorder_by_odd_even(items):
"""Reorders a list so that elements at odd indices come first,
followed by elements at even indices (1-based).
Example: [0,1,2,3,4,5,6] -> [1,3,5,0,2,4,6]
"""
odds = [items[i] for i in range(1, len(items), 2)]
evens = [items[i] for i in range(0, len(items), …
Segregate Negative Numbers Before Positives in Python
Reorders a list so all negative numbers appear before non-negative numbers while preserving the original relative order of elements.
def segregate_negatives(numbers):
"""Segregate negatives before positives without altering relative order."""
negatives = [n for n in numbers if n < 0]
positives = [n for n in numbers if n >= 0]
return negatives + positives
if __name__ == "__main__":
sample = [3, -1, 4, -5, 2, -9, 0]
result =…
Stable merge two lists by custom comparator in Python
Merge two lists into one sorted output using a custom comparator while maintaining the original order of equal elements.
from functools import cmp_to_key
def compare(x, y):
# Custom comparator: sorts by length first, then by original index for stability
if len(x) != len(y):
return len(x) - len(y)
return 0 # Equal keys preserve original order (stable)
def merge_stable(left, right, cmp_func):
result = []
i =…
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.