Reference library

Python Code Samples

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

171 matches
Dictionaries & sets easy

How to Use Dictionaries and Sets in Python for Beginners

Introduces Python dictionaries and sets with practical examples including creating, modifying, and performing set operations, plus a word-frequency counter.

dictionaries sets data structures
Python
def demonstrate_dict_sets():
    # Create a dictionary with basic info
    person = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    print("Dictionary:", person)

    # Access and modify dictionary values
    person["age"] = 31
    person["email"] = "alice@example.com"
    print("Afte…
15 0 Open
Dictionaries & sets easy

How to Use a Frozenset as a Dict Key in Python

Demonstrates using an immutable frozenset as a hashable dictionary key, including equality and lookup with differently-ordered elements.

frozenset dictionary hashable
Python
frozen = frozenset({"a", "b", "c"})
mapping = {frozen: "set as hashable key"}
other_frozen = frozenset(["c", "b", "a"])
print(f"Are keys equal? {frozen == other_frozen}")
print(f"Lookup with different order: {mapping[other_frozen]}")
print(f"Hash matches: {hash(frozen) == hash(other_frozen)}")
13 0 Open
Dictionaries & sets easy

How to Use defaultdict(set) in Python to Group Unique Values

Group key-value pairs into a dictionary of sets, automatically creating a new set for each key using defaultdict.

defaultdict sets dictionaries
Python
from collections import defaultdict

def track_groups(pairs):
    groups = defaultdict(set)
    for key, value in pairs:
        groups[key].add(value)
    return groups

if __name__ == "__main__":
    data = [
        ("fruit", "apple"),
        ("fruit", "banana"),
        ("fruit", "apple"),
        ("veg", "carrot…
15 0 Open
Dictionaries & sets easy

How to Validate Text and Count Words in Python

Count word frequencies, find unique and repeated words in a text using Python dictionaries and sets for beginner text validation.

dictionaries sets text-processing
Python
def validate_text(text):
    words = text.lower().split()
    
    word_counts = {}
    for word in words:
        cleaned = word.strip('.,!?;:"\'')
        if cleaned:
            word_counts[cleaned] = word_counts.get(cleaned, 0) + 1
    
    unique_words = set(word_counts.keys())
    repeated_words = {word for word…
12 0 Open
Dictionaries & sets easy

How to count words and find unique words in Python

Build a beginner-friendly text processor that counts word frequencies, finds unique words, and identifies words with vowels using dictionaries and sets.

dictionary set text-processing
Python
def text_processor(text):
    words = text.lower().replace(",", "").replace(".", "").split()
    word_count = {}
    
    for word in words:
        word_count[word] = word_count.get(word, 0) + 1
    
    unique_words = set(words)
    vowels = set("aeiou")
    words_with_vowels = {word for word in unique_words if vowe…
12 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…
12 0 Open
Dictionaries & sets easy

Multiset with Counter update and elements in Python

Demonstrates using collections.Counter as a multiset: updating counts with update() and iterating elements() to get repeated items.

counter multiset collections
Python
from collections import Counter

multiset = Counter(['apple', 'banana', 'apple'])

multiset.update(['banana', 'cherry', 'apple'])

print("Elements after update:", sorted(multiset.elements()))
print("Counts:", dict(multiset))
print("Most common:", multiset.most_common(2))
13 0 Open
Dictionaries & sets easy

Serialize Python dict to JSON with custom default for datetime

Convert a Python dict containing datetime and set objects into JSON by providing a custom default serializer.

json datetime serialization
Python
import json
from datetime import datetime

def custom_serializer(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    if isinstance(obj, set):
        return list(obj)
    return str(obj)

data = {
    "name": "Alice",
    "created_at": datetime(2024, 3, 15, 10, 30, 45),
    "tags": {"python", "j…
15 0 Open
Dictionaries & sets easy

Text Processor with Dictionaries and Sets in Python

Build a simple text processor that counts word frequencies with a dictionary and tracks unique words with a set.

dictionary set word-count
Python
def analyze_text(text):
    words = text.lower().split()
    word_freq = {}
    unique_words = set()
    
    for word in words:
        clean_word = word.strip('.,!?;:')
        if clean_word:
            word_freq[clean_word] = word_freq.get(clean_word, 0) + 1
            unique_words.add(clean_word)
    
    return…
12 0 Open
Dictionaries & sets medium

Unflatten Dot Keys to Nested Dict in Python

Convert a flat dictionary with dot-separated keys into a nested dictionary structure using recursive setdefault loops.

dictionaries nested flatten
Python
def unflatten_dot_keys(flat_dict):
    result = {}
    for flat_key, value in flat_dict.items():
        parts = flat_key.split(".")
        current = result
        for part in parts[:-1]:
            current = current.setdefault(part, {})
        current[parts[-1]] = value
    return result


if __name__ == "__main_…
14 0 Open
Dictionaries & sets easy

Validate dictionary data with sets in Python

Validate a dictionary against required keys and allowed value sets, returning a list of validation errors.

dictionaries sets validation
Python
def validate_data(data, required_keys, allowed_values=None):
    """
    Validate a dictionary against required keys and optional allowed value sets.
    Returns a list of validation errors (empty list if valid).
    """
    errors = []
    
    # Check for missing required keys
    missing = set(required_keys) - set(…
14 0 Open
OOP & classes easy

Add property getter setter validation in Python

Shows how to use @property with a setter to validate values before assigning them in a Python class.

property validation oop
Python
class Temperature:
    def __init__(self, celsius=0):
        self._celsius = celsius  # Use underscore to avoid recursion
    
    @property
    def celsius(self):
        """Getter returns the stored value."""
        return self._celsius
    
    @celsius.setter
    def celsius(self, value):
        """Setter valid…
16 0 Open
OOP & classes easy

Design a Data Helper Class in Python

Create a simple Object-Oriented data helper with DataPoint and Dataset classes that store, describe, and summarize coordinate points.

oop classes data-helper
Python
class DataPoint:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.label = None

    def describe(self):
        """Return a human-readable description of the data point."""
        base = f"DataPoint(x={self.x}, y={self.y})"
        return f"{base}, label='{self.label}'" if self.label e…
15 0 Open
OOP & classes easy

How to Call a Parent Class __init__ with super() in Python

Shows how to chain __init__ calls through a class hierarchy using super(), so each class sets its own attributes while reusing the parent's initialization logic.

oop inheritance super
Python
class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species
        print(f"Animal init: {self.name}, {self.species}")

class Mammal(Animal):
    def __init__(self, name, species, fur_color):
        super().__init__(name, species)
        self.fur_color = fur_color
   …
13 0 Open
OOP & classes easy

How to Define a Simple Python Class with __init__ and __repr__

Define a basic Python class with an __init__ method to set instance attributes and a __repr__ method for a readable representation of objects.

classes oop init
Python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Person(name={self.name!r}, age={self.age!r})"


if __name__ == "__main__":
    person = Person("Alice", 30)
    print(person)
15 0 Open
OOP & classes easy

How to Make a Python Class Hashable with __eq__ and __hash__

Define __eq__ and __hash__ together on a Python class so equal instances share the same hash and work correctly in sets and dictionary keys.

oop hashable eq
Python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        if not isinstance(other, Point):
            return NotImplemented
        return self.x == other.x and self.y == other.y

    def __hash__(self):
        return hash((self.x, self.y))

    def __repr…
13 0 Open
OOP & classes medium

How to Use __getstate__ and __setstate__ for Pickle in Python

Customize Python object serialization with the pickle __getstate__ and __setstate__ hooks to control exactly what data is stored and how it is restored.

pickle serialization getstate
Python
import pickle

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    def __getstate__(self):
        """Customize what gets pickled."""
        state = self.__dict__.copy()
        # Convert to Fahrenheit for storage (simulate transformation)
        state['fahrenheit'] = (self.celsiu…
13 0 Open
Algorithms & data structures easy

Filter List to Keep Only Whitelist Values in Python

Filter a list of values to keep only those present in a predefined whitelist set using a list comprehension.

filtering sets list-comprehension
Python
def filter_whitelist(values, whitelist):
    """Return only values that are present in the whitelist set."""
    return [value for value in values if value in whitelist]

if __name__ == "__main__":
    raw_values = ["apple", "banana", "cherry", "date", "apple", "elderberry"]
    allowed = {"apple", "banana", "date"}

…
11 0 Open
Algorithms & data structures easy

Find Elements in One Python List but Not Another

Return a new list containing only the elements from list A that are not present in list B, preserving duplicates and order.

list difference set membership filtering
Python
def difference_elements(a, b):
    """Return elements present in list a but not in list b."""
    set_b = set(b)
    return [item for item in a if item not in set_b]

if __name__ == "__main__":
    a = [1, 2, 3, 4, 5, 3, 2]
    b = [2, 4, 6]
    result = difference_elements(a, b)
    print(f"A: {a}")
    print(f"B: {b…
14 0 Open
Algorithms & data structures easy

Find Longest Consecutive Run in an Unsorted List in Python

Find the length of the longest sequence of consecutive integers in an unsorted list using a set and a linear scan.

set consecutive linear-scan
Python
def longest_run(nums):
    if not nums:
        return 0

    num_set = set(nums)
    longest = 0

    for num in num_set:
        # Only start counting from the smallest number in a sequence
        if num - 1 not in num_set:
            current = num
            length = 1
            while current + 1 in num_set:
 …
11 0 Open
Algorithms & data structures medium

Find Longest Consecutive Sequence in Python

Find the length of the longest consecutive elements sequence in an unsorted array using a set for O(n) lookups.

set longest-sequence hash-table
Python
def longest_consecutive_length(nums):
    num_set = set(nums)
    longest = 0
    
    for num in num_set:
        if num - 1 not in num_set:
            current = num
            current_streak = 1
            
            while current + 1 in num_set:
                current += 1
                current_streak += 1
…
13 0 Open
Algorithms & data structures medium

Find Missing Numbers, Duplicates, and Ranges in Python

Analyze a list to identify missing numbers, duplicate values, and contiguous ranges using sets and the Counter class.

algorithms sets counting
Python
def find_missing_duplicates_ranges(numbers):
    """Find missing numbers, duplicates, and ranges in a list."""
    from collections import Counter
    
    if not numbers:
        return {"missing": [], "duplicates": [], "ranges": []}
    
    full_range = set(range(min(numbers), max(numbers) + 1))
    present = set(n…
12 0 Open
Algorithms & data structures easy

Find the Second Largest Unique Number in a Python List

This Python function finds the second largest unique number from a list by converting it to a set, removing the maximum, and returning the new maximum.

set max unique
Python
def second_largest_unique(numbers):
    unique_numbers = set(numbers)
    if len(unique_numbers) < 2:
        return None
    unique_numbers.remove(max(unique_numbers))
    return max(unique_numbers)

if __name__ == "__main__":
    test_list = [4, 2, 9, 5, 2, 9, 1, 5]
    result = second_largest_unique(test_list)
    …
13 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…
17 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.