Reference library

Algorithms & data structures

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

3 matches
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

Split a String into Multiple Lines by Width in Python

Demonstrates a word-wrap algorithm that splits a message into rows without exceeding a maximum width.

strings word-wrap algorithm
Python
def split_message(text, max_width):
    words = text.split()
    rows = []
    current_row = []

    for word in words:
        if len(" ".join(current_row + [word])) > max_width:
            rows.append(" ".join(current_row))
            current_row = [word]
        else:
            current_row.append(word)

    if …
14 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.