Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

2 matches
Dictionaries & sets medium

How to Recursively Remove None Values from Nested Dictionaries in Python

Recursively removes all None values from nested dictionaries and lists while preserving non-None data.

dictionaries recursion data-cleaning
Python
def prune_none(obj):
    if isinstance(obj, dict):
        return {
            k: prune_none(v)
            for k, v in obj.items()
            if v is not None and prune_none(v) is not None
        }
    elif isinstance(obj, list):
        pruned = [prune_none(item) for item in obj]
        pruned = [item for item i…
15 0 Open
Algorithms & data structures medium

How to Find the Previous Smaller Element in Python

Use a monotonic stack to find the nearest smaller element to the left of each item in a list, returning -1 when none exists.

monotonic stack stack arrays
Python
from collections import deque

def previous_smaller_elements(arr):
    stack = deque()
    result = [-1] * len(arr)

    for i in range(len(arr)):
        while stack and arr[stack[-1]] >= arr[i]:
            stack.pop()
        if stack:
            result[i] = arr[stack[-1]]
        stack.append(i)

    return resul…
15 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

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.