Reference library

Algorithms & data structures

Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.

13 matches
Algorithms & data structures easy

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.

counter intersection nested-lists
Python
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 _…
13 0 Open
Algorithms & data structures easy

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.

pascal-triangle dynamic-programming algorithms
Python
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__":
…
14 0 Open
Algorithms & data structures easy

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.

list zip list-comprehension
Python
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)
12 0 Open
Algorithms & data structures easy

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.

lists comparison zip
Python
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"…
13 0 Open
Algorithms & data structures easy

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.

jaccard sets similarity
Python
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…
17 0 Open
Algorithms & data structures easy

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.

itertools cartesian-product combinations
Python
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)
15 0 Open
Algorithms & data structures easy

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.

dot product zip sum
Python
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__":
  …
13 0 Open
Algorithms & data structures easy

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.

flatten dictionaries lists
Python
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": …
12 0 Open
Algorithms & data structures easy

How to Implement a Recent Counter with a Deque in Python

Implements a RecentCounter class that uses a deque to count ping requests within the last 3000 milliseconds.

deque recents sliding-window
Python
from collections import deque
import time


class RecentCounter:
    def __init__(self):
        self.hits = deque()

    def ping(self, t: int) -> int:
        self.hits.append(t)
        while self.hits and self.hits[0] < t - 3000:
            self.hits.popleft()
        return len(self.hits)


if __name__ == "__mai…
11 0 Open
Algorithms & data structures easy

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.

list predicate partition
Python
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…
11 0 Open
Algorithms & data structures easy

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.

list indices reorder
Python
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), …
18 0 Open
Algorithms & data structures easy

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.

lists partition stability
Python
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 =…
14 0 Open
Algorithms & data structures easy

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.

merge stable-sort custom-comparator
Python
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 =…
13 0 Open

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.