Python playground

Practice algorithms and Python syntax in one place.

Pick a snippet, tweak the code, and run it in the browser. Great for refreshing core syntax and algorithm muscle memory.

How to use

  1. Pick a snippet from the library.
  2. Edit the code or add your own test cases.
  3. Run the code and inspect output.

Jump to a section

Fundamentals, playground drills, and walkthroughs in one flow.

Python syntax and features

Concise language tools that show up often in backend codebases.

Syntax

Comprehensions

Python offers concise syntax for building sequences.

  • List comprehensions build lists with an expression, loop, and optional condition.
  • Example: squares of even numbers.
  • Also useful: dict comprehensions ({k: v for ...}) and set comprehensions ({x for ...}).
Example
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
print(even_squares)  # [0, 4, 16, 36, 64]
Syntax

Decorators

Decorators wrap functions or methods to add behavior without changing call sites.

  • Use for logging, auth, caching, or tracing.
  • Backend-relevant built-ins: @staticmethod, @classmethod, @property.
Example
def log_calls(func):
    def wrapper(*args, **kwargs):
        print(f"Starting {func.__name__}")
        result = func(*args, **kwargs)
        print(f"Finished {func.__name__}")
        return result
    return wrapper


@log_calls
def greet(name):
    print(f"Hello, {name}!")


greet("Alice")
Syntax

Context managers (with)

Use with to guarantee cleanup of resources, even on exceptions.

  • Great for files, DB connections, and locks.
  • Custom context managers implement __enter__ and __exit__.
Example
with open("data.txt", "r") as f:
    lines = f.readlines()
# closed automatically
Syntax

Lambda functions

Anonymous, one-line functions for key functions or small transforms.

Example
items = [("a", 3), ("b", 1), ("c", 2)]
sorted_items = sorted(items, key=lambda x: x[1])
print(sorted_items)  # [("b", 1), ("c", 2), ("a", 3)]
Syntax

Type hints

Improve readability and tooling support.

Example
from typing import Any, Dict


def greeting(name: str) -> str:
    return "Hello, " + name


payload: Dict[str, Any] = {"id": 1, "ok": True}
Syntax

Exception handling

Catch expected errors and avoid overly broad exceptions.

Example
try:
    value = int(user_input)
except ValueError as e:
    print("Invalid input:", e)
finally:
    print("Execution complete")
Syntax

High-value built-ins

Reach for map, filter, zip, and enumerate when transforms get repetitive.

  • Note: map, filter, and zip return iterators in Python 3.
Example
nums = [1, 2, 3]
doubled = list(map(lambda x: x * 2, nums))
odds = list(filter(lambda x: x % 2, nums))
paired = list(zip(nums, ["a", "b", "c"]))
print(doubled)  # [2, 4, 6]
print(odds)  # [1, 3]
print(paired)  # [(1, "a"), (2, "b"), (3, "c")]

for idx, val in enumerate(nums, start=1):
    print(idx, val)

Python data structures

Core containers, performance expectations, and small sketches.

Data structure

Lists (list)

Mutable ordered sequence.

  • Key ops: append, pop, insert, remove, slicing, sort.
  • Stack (LIFO) pattern with list.
Example
stack = []
stack.append(1)
stack.append(2)
print(stack.pop())  # 2
Data structure

Dictionaries (dict)

Hash map for fast key lookup.

  • Key ops: get, items, keys, values, update, pop.
Example
user_ages = {"Alice": 30, "Bob": 25}
print(user_ages.get("Alice"))  # 30
Data structure

Sets (set)

Unordered unique elements with fast membership tests.

Example
s = {1, 2, 3, 2}
print(2 in s)    # True
print(s | {3, 4})  # {1, 2, 3, 4}
Data structure

Tuples (tuple)

Immutable ordered sequence for fixed records and dict keys.

Example
coords = (10.0, 20.0)
print(coords[0])  # 10.0
Data structure

Queues (collections.deque)

FIFO structure with efficient pops from the left.

Example
from collections import deque

queue = deque([1, 2, 3])
queue.append(4)
print(queue.popleft())  # 1
Data structure

Heaps (heapq)

Min-heap priority queue implementation.

Example
import heapq

heap = []
heapq.heappush(heap, 5)
heapq.heappush(heap, 3)
heapq.heappush(heap, 10)
print(heapq.heappop(heap))  # 3
Data structure

Linked lists (custom)

No built-in type, so implement nodes with pointers.

Example
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None


n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n1.next = n2
n2.next = n3

Use when you need frequent insert/delete with pointers, or for pointer practice.

Data structure

Trees

Hierarchical structure. Binary trees have up to two children.

Example
class TreeNode:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None


root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(15)

Common traversals: preorder, inorder, postorder, and BFS level order.

Data structure

Graphs

Nodes and edges to model networks and dependencies.

Example
graph = {
    "A": ["B", "C"],
    "B": ["A", "D"],
    "C": ["A", "D"],
    "D": ["B", "C"],
}

Traversal: BFS or DFS with an adjacency list.

Sample coding problems (backend style)

Practice patterns you will use for services, queues, caches, and data transforms.

Problem

Aggregate totals per user

Given orders with user and price, compute total spend per user.

Example
orders = [
    {"user": "Alice", "price": 50},
    {"user": "Bob", "price": 75},
    {"user": "Alice", "price": 100},
    {"user": "Bob", "price": 25},
]

totals = {}
for order in orders:
    user = order["user"]
    totals[user] = totals.get(user, 0) + order["price"]

print(totals)  # {"Alice": 150, "Bob": 100}
Problem

LRU cache (O(1) get and put)

Use OrderedDict to track recency and evict oldest entries.

Example
from collections import OrderedDict


class LRUCache:
    def __init__(self, capacity=3):
        self.cache = OrderedDict()
        self.capacity = capacity

    def get(self, key):
        if key not in self.cache:
            return -1
        self.cache.move_to_end(key)
        return self.cache[key]

    def put(self, key, value):
        if key in self.cache:
            self.cache.move_to_end(key)
        self.cache[key] = value
        if len(self.cache) > self.capacity:
            self.cache.popitem(last=False)


cache = LRUCache(capacity=2)
cache.put("a", 1)
cache.put("b", 2)
print(cache.get("a"))  # 1
cache.put("c", 3)      # evicts "b"
print(list(cache.cache.keys()))  # ["a", "c"]
Problem

FIFO task processing

Use deque for efficient queue behavior.

Example
from collections import deque

tasks = deque(["task1", "task2"])
tasks.append("task3")

while tasks:
    current = tasks.popleft()
    print("Processing:", current)
Problem

Flatten nested list

Common for nested JSON arrays.

Example
def flatten(nested):
    flat = []
    for item in nested:
        if isinstance(item, list):
            flat.extend(flatten(item))
        else:
            flat.append(item)
    return flat


nested = [1, [2, 3], [4, [5, 6]]]
print(flatten(nested))  # [1, 2, 3, 4, 5, 6]
Problem

Endpoint caching via lru_cache

Memoize expensive calls such as DB or remote fetches.

Example
from functools import lru_cache


@lru_cache(maxsize=100)
def fetch_user_data(user_id):
    print(f"Fetching data for {user_id}")
    return {"id": user_id, "data": "..."}


fetch_user_data(42)  # hits expensive path
fetch_user_data(42)  # served from cache

Quick learning checklist

Use this as a final sweep before you practice in the playground.

  • Know time and space complexity for list, dict, set, deque, and heap operations.
  • Comfortable with collections (deque, Counter, defaultdict, OrderedDict), heapq, and functools (lru_cache).
  • Write clean solutions using enumerate, zip, comprehensions, and safe dict access via get.
  • Practice robust error handling for expected failures.

Python playground

Run small exercises for syntax, data structures, and algorithms.

Active snippet

Syntax

Select a snippet to begin

Use the editor to experiment with the code.

Loading Python runtime...

Output

stdout and errors appear here.

Run code to see output.

Walkthrough library

Open any card, review the guidance, then load the code into the editor to practice.

Open the Python sketch inside a card and use the "Load in editor" button to practice.

Data structures walkthrough

Core storage models, operations, and pitfalls.

Algorithms walkthrough

Step-by-step procedures with complexity and Python sketches.

Patterns walkthrough

Reusable problem-solving strategies, signals, and pitfalls.