Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
Binary Tree Inorder Traversal in Python
Define a TreeNode class and recursively print in-order traversal (left, node, right) of a binary tree.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_traversal(root):
return inorder_traversal(root.left) + [root.val] + inorder_traversal(root.right) if root else []
if __name__ == "__main__":
# Build a…
Depth First Search Traversal Order in Python
Recursive depth-first search that returns the visit order of nodes in an adjacency list graph starting from a given node.
def dfs_order(adj, start):
visited = set()
order = []
def dfs(node):
visited.add(node)
order.append(node)
for neighbor in adj.get(node, []):
if neighbor not in visited:
dfs(neighbor)
dfs(start)
return order
if __name__ == "__main__":
# Dem…
How to Get the Breadth-First Traversal Order of a Graph in Python
Performs a breadth-first search on an adjacency list and returns the order nodes are visited, using a deque for efficient queue operations.
from collections import deque
def bfs_order(adjacency, start=0):
"""Return the order nodes are visited in a breadth-first traversal."""
visited = set()
order = []
queue = deque([start])
visited.add(start)
while queue:
node = queue.popleft()
order.append(node)
for neig…
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.