Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

10 matches
Strings & text easy

How to Join List of Words into a Sentence in Python

Concatenate a list of strings into a single sentence with spaces using the Python string join() method.

string join list
Python
words = ["Hello", "world", "this", "is", "Python"]
sentence = " ".join(words)
print(sentence)
15 0 Open
Lists & loops easy

How to Partition a List Around a Pivot in Python

This code splits a list into three parts—elements less than, equal to, and greater than a pivot—then concatenates them to produce a partitioned list while preserving the original order within each group.

partition list pivot
Python
def partition_list(lst, pivot):
    less = []
    equal = []
    greater = []
    for item in lst:
        if item < pivot:
            less.append(item)
        elif item == pivot:
            equal.append(item)
        else:
            greater.append(item)
    return less + equal + greater

if __name__ == "__main__…
14 0 Open
Functions & basics easy

How to Merge Lists in Python with Default Parameters

This Python function merges two lists using the + operator and demonstrates default parameters, allowing the second argument to be omitted.

functions default-parameters list
Python
def merge_lists(list1, list2=["default"]):
    """Merge two lists and return the combined result."""
    return list1 + list2


if __name__ == "__main__":
    # Example with default parameter
    print("With default:", merge_lists([1, 2, 3]))
    
    # Example with both arguments provided
    print("With custom:", me…
14 0 Open
Functions & basics easy

How to Use functools.reduce in Python

Apply functools.reduce with operator functions and lambda expressions to aggregate lists into sums, products, maximums, and concatenated strings.

reduce functools lambda
Python
from functools import reduce
import operator

# Sum all numbers in a list using reduce
numbers = [1, 2, 3, 4, 5]
sum_result = reduce(operator.add, numbers)

# Find the maximum value using reduce
max_result = reduce(lambda a, b: a if a > b else b, numbers)

# Multiply all numbers using reduce
product_result = reduce(la…
12 0 Open
Files & data easy

How to Extract Text from PDF Files in Python

Extract all readable text from a PDF file using PyPDF2, iterating over each page and concatenating the content.

pdf text-extraction pypdf2
Python
import PyPDF2

def extract_text_from_pdf(pdf_path):
    text = ""
    with open(pdf_path, "rb") as file:
        reader = PyPDF2.PdfReader(file)
        for page in reader.pages:
            text += page.extract_text() + "\n"
    return text.strip()

if __name__ == "__main__":
    pdf_path = "sample.pdf"
    extracted…
52 0 Open
Files & data easy

Reassemble File Parts into Original File Bytes in Python

Read sorted part files from a directory and concatenate their bytes into the original file.

file handling binary byte concatenation
Python
import os
import sys
from pathlib import Path

def reassemble_parts(parts_dir: Path, output_path: Path) -> int:
    """
    Reassemble file parts into the original file.

    Args:
        parts_dir: Directory containing the part files
        output_path: Path where the reassembled file will be written

    Returns:
…
12 0 Open
Algorithms & data structures easy

Reorder a List by Odd Even Indices in Python

Splits a list into two sublists based on 1-based index parity, then concatenates odd-indexed elements before even-indexed ones.

list indices reorder
Python
def reorder_by_odd_even(items):
    """Reorders a list so that elements at odd indices come first,
    followed by elements at even indices (1-based).
    
    Example: [0,1,2,3,4,5,6] -> [1,3,5,0,2,4,6]
    """
    odds = [items[i] for i in range(1, len(items), 2)]
    evens = [items[i] for i in range(0, len(items), …
18 0 Open
AI & LLM integration patterns easy

How to Accumulate Streamed Tokens into a Final String in Python

Accumulate a stream of tokens into a single final string by concatenating each token in sequence.

streaming tokens strings
Python
def accumulate_tokens(tokens):
    """Accumulate a stream of tokens into a single final string."""
    result = ""
    for token in tokens:
        result += token
    return result


if __name__ == "__main__":
    token_stream = ["Hello", ", ", "world", "!", " This ", "is ", "accumulated."]
    final_string = accumul…
16 0 Open
Automation & scripting easy

How to Merge PDFs in Python (Mock pypdf Stub)

Merge PDF files by concatenating their raw byte content using a simple stubbed class that mimics the pypdf interface.

pdf merge mock
Python
import io
from hashlib import sha256


class PdfStub:
    def __init__(self, data: bytes, name: str):
        self.data = data
        self.name = name

    def get_content_bytes(self) -> bytes:
        return self.data


def merge_pdfs_mock(pdf_stubs) -> bytes:
    merged = io.BytesIO()
    for stub in pdf_stubs:
   …
14 0 Open
Data pipelines & processing easy

Union Multiple DataFrames with Aligned Columns in Python

Concatenate DataFrames with different columns, aligning them and filling missing values with NaN using pandas concat.

pandas dataframes concat
Python
import pandas as pd
from io import StringIO

# Sample dataframes with different columns
df1 = pd.DataFrame({
    'id': [1, 2, 3],
    'name': ['Alice', 'Bob', 'Charlie'],
    'age': [25, 30, 35]
})

df2 = pd.DataFrame({
    'id': [4, 5],
    'name': ['Diana', 'Eve'],
    'city': ['NYC', 'LA']
})

df3 = pd.DataFrame({
…
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.