Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Convert Data to Strings in Python
Convert common data types like bytes, numbers, containers, and None to readable strings with a safe helper function.
def to_str(value):
"""Convert common types to a readable string, safe for beginners."""
if isinstance(value, bytes):
return value.decode("utf-8")
if isinstance(value, (dict, list, tuple, set)):
return str(value)
if value is None:
return ""
return str(value)
if __name__ == …
How to Filter Docker Containers for Pruning in Python
Simulate Docker's container prune by filtering a JSON list for exited containers older than a cutoff, returning pruned IDs and space freed.
import json
from datetime import datetime, timedelta
def parse_docker_ps(json_output: str, older_than_hours: int = 24) -> list:
containers = json.loads(json_output)
cutoff = datetime.now() - timedelta(hours=older_than_hours)
return [
c for c in containers
if datetime.fromisoformat(c["crea…
How to Mock a Container Registry in Python
Build an in-memory container registry mock with push, tag listing, and manifest retrieval logic for testing deployment tooling.
import json
from collections import defaultdict
class MockRegistry:
def __init__(self):
self.repositories = defaultdict(dict)
def push_image(self, repo: str, tag: str, layers: list[str]) -> None:
self.repositories[repo][tag] = {
"layers": layers,
"size": sum(len(layer…
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.