Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

9 matches
Strings & text easy

How to Check Palindrome in Python (Ignore Case and Spaces)

Check whether a string is a palindrome while ignoring case, spaces, and all non-alphanumeric characters using Python's filter and string reversal.

palindrome string case-insensitive
Python
def is_palindrome(text: str) -> bool:
    cleaned = ''.join(char.lower() for char in text if char.isalnum())
    return cleaned == cleaned[::-1]

if __name__ == "__main__":
    test_cases = [
        "A man, a plan, a canal: Panama",
        "race a car",
        "Was it a car or a cat I saw?",
        "hello",
      …
14 0 Open
Strings & text easy

Reverse Words in a Sentence While Keeping Punctuation in Python

Reverses the order of words in a sentence while leaving punctuation and spaces in their original positions using Python's re module.

strings punctuation regex
Python
def reverse_words_preserving_punctuation(sentence: str) -> str:
    import re
    # Split into words and punctuation tokens
    tokens = re.findall(r'\w+|[^\w\s]|\s+', sentence)
    words = [t for t in tokens if re.fullmatch(r'\w+', t)]
    words.reverse()
    result_parts = []
    word_index = 0
    for token in toke…
13 0 Open
Strings & text easy

Text Processor Functions for Beginners in Python

Demonstrates simple text-processing utilities: word counting, word reversal, whitespace normalization, and lowercase conversion using basic string methods.

text-processing string-methods word-count
Python
def count_words(text):
    """Return the number of words in a string."""
    return len(text.split())

def reverse_words(text):
    """Return the text with words in reverse order."""
    return ' '.join(text.split()[::-1])

def remove_extra_spaces(text):
    """Return text with extra whitespace collapsed to a single s…
13 0 Open
OOP & classes easy

Binary Tree Inorder Traversal in Python

Define a TreeNode class and recursively print in-order traversal (left, node, right) of a binary tree.

binary-tree recursion traversal
Python
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…
15 0 Open
Algorithms & data structures easy

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.

dfs graph traversal
Python
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…
16 0 Open
Algorithms & data structures easy

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.

graph bfs queue
Python
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…
14 0 Open
AI & LLM integration patterns easy

How to Build a System-User-Assistant Message List in Python

Use dataclasses to model a chat conversation and build the system/user/assistant message list expected by LLM APIs.

llm dataclass openai
Python
from dataclasses import dataclass, field
from typing import List


@dataclass
class Message:
    role: str
    content: str


@dataclass
class Conversation:
    messages: List[Message] = field(default_factory=list)

    def add_system(self, content: str) -> None:
        self.messages.append(Message(role="system", con…
13 0 Open
AI & LLM integration patterns easy

How to Keep Last K Turns in a Memory Buffer in Python

A TurnBuffer class using deque with maxlen to keep only the most recent k conversation turns in memory for LLM context.

deque llm-context memory-buffer
Python
from collections import deque

class TurnBuffer:
    def __init__(self, k):
        self.k = k
        self.turns = deque(maxlen=k)

    def add(self, turn):
        self.turns.append(turn)

    def last_k(self):
        return list(self.turns)


if __name__ == "__main__":
    buffer = TurnBuffer(3)
    buffer.add("tu…
14 0 Open
AI & LLM integration patterns easy

How to Summarize Old Conversation Turns in Python

Compress old conversation turns into a brief summary while keeping recent turns intact for LLM context management.

llm context compression
Python
from datetime import datetime, timedelta


def summarize_old_turns(conversation, max_turns=5):
    """Compress turns older than max_turns into a brief summary."""
    if len(conversation) <= max_turns:
        return conversation, ""

    old_turns = conversation[:-max_turns]
    recent_turns = conversation[-max_turns…
14 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.