Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Flatten One Level of a Nested List in Python
Flattens exactly one level of a nested list by extending the output with each inner list and appending non-list items.
def flatten_one_level(nested_list):
"""Flatten one level of a nested list."""
flattened = []
for item in nested_list:
if isinstance(item, list):
flattened.extend(item)
else:
flattened.append(item)
return flattened
if __name__ == "__main__":
# Example with mi…
How to Flatten a Deeply Nested List in Python Recursively
A recursive function that flattens arbitrarily deep nested lists into a single flat list using isinstance checks.
def flatten(nested_list):
if not nested_list:
return []
if isinstance(nested_list[0], list):
return flatten(nested_list[0]) + flatten(nested_list[1:])
return [nested_list[0]] + flatten(nested_list[1:])
if __name__ == "__main__":
data = [1, [2, [3, [4, [5]]]], [6, [7, [8, [9]]]], 10]
…
Flatten a Nested Dict to Dot Notation Keys in Python
Recursively flatten a nested dictionary into a flat dictionary with dot-separated keys using a small recursive function.
def flatten_dict(nested, parent_key='', sep='.'):
items = {}
for key, value in nested.items():
new_key = f"{parent_key}{sep}{key}" if parent_key else key
if isinstance(value, dict):
items.update(flatten_dict(value, new_key, sep))
else:
items[new_key] = value
…
Unflatten Dot Keys to Nested Dict in Python
Convert a flat dictionary with dot-separated keys into a nested dictionary structure using recursive setdefault loops.
def unflatten_dot_keys(flat_dict):
result = {}
for flat_key, value in flat_dict.items():
parts = flat_key.split(".")
current = result
for part in parts[:-1]:
current = current.setdefault(part, {})
current[parts[-1]] = value
return result
if __name__ == "__main_…
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.
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": …
Flatten a Nested List in Python (Recursive Generator)
Recursively flatten arbitrarily nested lists into a single-level list using both a function and a generator with `yield from`.
def flatten(nested_list):
"""Recursively flatten a nested list into a single-level list."""
result = []
for item in nested_list:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
def flatten_generator(nested_list):
…
How to Delegate Iteration to a Subgenerator with yield from in Python
Use yield from to delegate iteration from one generator to a subgenerator, flattening nested generator output into a single sequence.
def subgenerator():
yield "first"
yield "second"
yield "third"
def delegate():
yield "before delegation"
yield from subgenerator()
yield "after delegation"
if __name__ == "__main__":
for item in delegate():
print(item)
How to Build a Data Helper for LLM Prompts in Python
A beginner-friendly helper class that flattens nested dictionaries, formats prompt templates, and safely parses JSON for AI/LLM pipelines.
import json
from typing import Any, Dict, List, Optional
class DataHelper:
"""Simple helper class for working with data in AI/LLM pipelines."""
def __init__(self, data: Optional[Dict[str, Any]] = None) -> None:
self.data = data or {}
def flatten(self, prefix: str = "") -> Dict[str, Any]…
How to Explode an Array Field into Multiple Rows in Python
This code flattens a list of dictionaries by exploding each array field value into its own row, duplicating the other fields as needed.
from collections import defaultdict
data = [
{"id": 1, "name": "Alice", "tags": ["python", "data", "ai"]},
{"id": 2, "name": "Bob", "tags": ["web", "devops"]},
{"id": 3, "name": "Carol", "tags": []},
]
def explode_array_field(records, array_field):
result = []
for record in records:
for v…
Simulate a GIN Index for JSONB in Python
Build a mock Generalized Inverted Index (GIN) that flattens JSON documents into key-value tokens for fast lookup queries, mimicking PostgreSQL JSONB indexing.
import json
import random
from collections import defaultdict
# Mock GIN (Generalized Inverted Index) for JSONB key-value pairs
class GINIndex:
def __init__(self):
self.posting_lists = defaultdict(list) # token -> list of doc_ids
def index(self, doc_id, json_obj):
"""Index a JSON documen…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.