Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Build CSV row from Python list with proper quoting
Converts a list of fields into a properly quoted CSV row string using the csv module.
import csv
import io
def build_csv_row(fields):
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(fields)
return output.getvalue().rstrip("\r\n")
if __name__ == "__main__":
fields = ["Alice", "Smith", "123 Main St, Apt 4B", "alice@example.com"]
print(build_csv_row(fields))
How to Load a YAML Subset in Python Without PyYAML
Parse a flat, key-value YAML file with the Python standard library (re and pathlib), handling comments, quotes, and inline comments while skipping nested structures.
import re
from pathlib import Path
def load_yaml_subset(path):
"""Load a flat YAML file (key: value) without external dependencies."""
data = {}
with open(path, 'r', encoding='utf-8') as f:
for line in f:
# Skip empty lines and comments
line = line.strip()
if no…
How to Repair Malformed JSON Braces Heuristically in Python
Heuristically fix malformed JSON by balancing braces and quotes, using a stack-based approach to add missing closing characters.
import json
import re
def repair_json(text: str) -> str:
"""Heuristically repair malformed JSON by balancing braces and quotes."""
# Trim whitespace and handle leading/trailing garbage
text = text.strip()
# Remove common non-JSON decorations
text = re.sub(r'^(
How to Load envrc Files in Python
Parse and apply direnv-style envrc files to the current environment, with proper handling of variables, comments, and quotes.
import os
import tempfile
from pathlib import Path
from unittest.mock import patch
def load_envrc(envrc_path):
"""Parse an envrc-style file and apply it to the current environment."""
env_changes = {}
with open(envrc_path, "r") as f:
for line in f:
line = line.strip()
if l…
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.