Reference library

Python Code Samples

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

10 matches
Lists & loops easy

How to Get the Union of Two Lists Without Duplicates in Python

Merge two lists and remove duplicate values using a set, then convert back to a list.

set union merge
Python
def union_without_duplicates(list1, list2):
    return list(set(list1 + list2))

if __name__ == "__main__":
    list_a = [1, 2, 3, 4]
    list_b = [3, 4, 5, 6]
    result = union_without_duplicates(list_a, list_b)
    print(f"Union of {list_a} and {list_b}: {result}")
12 0 Open
Dictionaries & sets easy

How to Compute Set Union of Tags from Multiple Items in Python

Collect all unique tags from a list of dictionaries using set union with update() in Python.

set union tags dictionaries
Python
items = [
    {"id": 1, "tags": {"python", "web"}},
    {"id": 2, "tags": {"web", "api", "sql"}},
    {"id": 3, "tags": {"python", "data"}},
]


def get_union_of_tags(item_list):
    all_tags = set()
    for item in item_list:
        all_tags.update(item["tags"])
    return all_tags


if __name__ == "__main__":
    u…
13 0 Open
Dictionaries & sets medium

How to Implement Disjoint Set Union Find in Python

Implement a Disjoint Set Union-Find data structure using a Python dictionary for parent tracking, with path compression and connectivity checks.

disjoint-set union-find graph
Python
class DisjointSet:
    def __init__(self):
        self.parent = {}

    def find(self, x):
        # Path compression
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]

    def union(self, x, y):
        # Initialize if not present
        if x not in…
13 0 Open
Dictionaries & sets easy

How to merge dictionaries and sets in Python

Merges multiple dictionaries with the ** unpacking operator and combines sets using union operations into a single structure.

dict-merge set-union unpacking
Python
def merge_dictionaries_and_sets(school_dict, teacher_dict, course_dict, student_sets):
    """
    Merges multiple dictionaries and sets into a single combined structure.
    Demonstrates dict unpacking and set union operations.
    """
    # Merge all dictionaries using the unpacking operator (Python 3.9+)
    merged…
11 0 Open
Algorithms & data structures easy

How to Compute Jaccard Similarity in Python

Compute the Jaccard similarity between two lists by converting them to sets and dividing the intersection size by the union size.

jaccard sets similarity
Python
def jaccard_similarity(list1, list2):
    set1 = set(list1)
    set2 = set(list2)
    
    intersection = set1 & set2
    union = set1 | set2
    
    if not union:
        return 0.0
    
    return len(intersection) / len(union)

if __name__ == "__main__":
    a = [1, 2, 3, 4, 5]
    b = [3, 4, 5, 6, 7]
    
    pri…
15 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({
…
13 0 Open
Testing & modern typing easy

Design Data Helpers with Python TypedDict and Literal

Use TypedDict, Literal, and Union to define typed data shapes and parse values in Python.

typeddict literal union
Python
from typing import TypedDict, Literal, Optional, Union, List

class User(TypedDict):
    name: str
    age: int
    role: Literal["admin", "user", "guest"]

def describeUser(data: User) -> str:
    return f"{data['name']} ({data['age']}) — {data['role']}"

def parse_value(item: Union[int, str, None]) -> str:
    if it…
12 0 Open
Testing & modern typing easy

How to Use Python Type Hints for Beginners

Build a data helper module with basic type hints — Union, Optional, List, Dict, Any, and TypeVar — to make your code clearer and safer.

type-hints typing annotations
Python
from typing import Any, Union, Optional, List, Dict, Tuple, Callable, TypeVar

T = TypeVar("T")

def describe(value: Any) -> str:
    """Return a human-readable description of the value's type."""
    if isinstance(value, list):
        return f"list of {len(value)} items"
    elif isinstance(value, dict):
        ret…
12 0 Open
Testing & modern typing easy

How to Use Union Type Hints in Python

This code demonstrates how to use Union type hints to specify that a parameter can accept multiple types (int, float, str) and handle them accordingly.

type-hints union typing
Python
from typing import Union

def process_value(value: Union[int, float, str]) -> str:
    if isinstance(value, (int, float)):
        return f"Number: {value * 2}"
    return f"String: {value.upper()}"

if __name__ == "__main__":
    print(process_value(10))
    print(process_value(3.14))
    print(process_value("hello"))
13 0 Open
Testing & modern typing easy

How to use Optional type hint in Python

Use the Optional type hint to indicate a parameter can be a string or None, with an example function that handles both cases.

typing optional type-hints
Python
from typing import Optional

def greet(name: Optional[str]) -> str:
    if name is None:
        return "Hello, anonymous!"
    else:
        return f"Hello, {name}!"

if __name__ == "__main__":
    print(greet("Alice"))
    print(greet(None))
10 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.