Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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 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 Compute a Confusion Matrix in Python
Compute a multi-class confusion matrix from true and predicted labels using pure Python dictionaries and nested lists, then format it for readable output.
from collections import defaultdict
def compute_confusion_matrix(y_true, y_pred, labels):
"""Compute confusion matrix using Python dicts and nested lists."""
label_index = {label: i for i, label in enumerate(labels)}
matrix = [[0] * len(labels) for _ in range(len(labels))]
for true, pred in zip(y…
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.