Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
Count Smaller Elements to the Right in Python
Return a list where each index counts how many elements to its right are smaller than that element using a clean O(n²) nested-loop approach.
def count_smaller_elements(arr):
"""
Return a list where result[i] is the number of elements
to the right of arr[i] that are smaller than arr[i].
"""
result = []
for i in range(len(arr)):
count = 0
for j in range(i + 1, len(arr)):
if arr[j] < arr[i]:
…
How to Build a Coordinate Grid with Nested Loops in Python
Generate a 2D list of (row, col) coordinate pairs using nested loops and return the grid structure.
def build_coordinate_grid(rows, cols):
"""Build a 2D grid of (row, col) coordinates using nested loops."""
grid = []
for r in range(rows):
row = []
for c in range(cols):
row.append((r, c))
grid.append(row)
return grid
if __name__ == "__main__":
grid = build_coo…
How to Generate Fibonacci Sequence in Python
Generate the first n Fibonacci numbers as a list using a simple iterative loop.
def fibonacci(n):
"""Generate the first n terms of the Fibonacci sequence."""
if n <= 0:
return []
seq = [0, 1]
while len(seq) < n:
seq.append(seq[-1] + seq[-2])
return seq[:n]
if __name__ == "__main__":
n = 10
result = fibonacci(n)
print(result)
How to Map Strings to Uppercase in Python
Loops through a list of strings and builds a new list with each string converted to uppercase.
strings = ["hello", "world", "python", "skillset"]
uppercased = []
for s in strings:
uppercased.append(s.upper())
print(uppercased)
Implement a Stack Using List Push Pop in Python
A minimal Stack class built on a Python list, with push, pop, peek, is_empty, and size methods, including empty-stack guards.
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if self.is_empty():
raise IndexError("pop from empty stack")
return self.items.pop()
def peek(self):
if self.is_empty():
raise…
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.