Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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.
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…
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.
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…
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.
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…
How to swap dict keys and values in Python when values are unique
Swap dict keys and values using a dict comprehension, with a guard that raises an error when values repeat.
def swap_dict_keys_values(d):
"""Swap keys and values in a dict, assuming values are unique."""
if len(set(d.values())) != len(d.values()):
raise ValueError("Values must be unique to swap keys and values")
return {v: k for k, v in d.items()}
if __name__ == "__main__":
original = {"a": 1, "b": …
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.
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…
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.
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)
…
How to Count Distinct Elements in a List in Python
Count the number of unique items in a list by converting it to a set and returning its length.
def count_distinct_elements(items):
return len(set(items))
if __name__ == "__main__":
sample = [1, 2, 3, 2, 1, 4, 3, 5, 4, 6]
result = count_distinct_elements(sample)
print(result)
How to Sample Random Items Without Replacement in Python
Select k random unique items from a sequence using random.sample for uniform, non-repeating selection.
import random
def sample_without_replacement(population, k):
"""Return k random items from population without replacement."""
if k > len(population):
raise ValueError("k cannot exceed population size")
# Use random.sample for O(k) time, no mutation of the original
return random.sample(populati…
Sort Unique Values by Frequency in Python
Count element frequencies with Counter and sort unique values by descending frequency, breaking ties alphabetically.
from collections import Counter
def sort_unique_by_frequency(values):
counts = Counter(values)
return sorted(counts.keys(), key=lambda x: (-counts[x], x))
if __name__ == "__main__":
data = [4, 2, 2, 8, 3, 3, 1, 3, 5, 5, 5, 5, 1]
result = sort_unique_by_frequency(data)
print(f"Sorted unique values…
Generate UUID4 Values with a Python Generator
This code defines a generator function that yields mock UUID4 values, allowing you to stream unique identifiers one at a time.
import uuid
def generate_uuids(count=5):
"""Generate a stream of mock UUID4 values."""
for _ in range(count):
yield uuid.uuid4()
if __name__ == "__main__":
# Generate and print 5 UUIDs
for uid in generate_uuids(5):
print(uid)
How to generate combinations in Python with itertools
Generate all unique combinations of r items from a given list using itertools.combinations.
import itertools
def combinations_generator(items, r):
return list(itertools.combinations(items, r))
if __name__ == "__main__":
items = ['A', 'B', 'C', 'D']
r = 2
result = combinations_generator(items, r)
for combo in result:
print(combo)
print(f"Total: {len(result)} combinations of {…
Set Comprehension for Unique Word Lengths in Python
Use a set comprehension to extract unique word lengths from a string, then sort and print the result.
text = "hello world hello python programming"
word_lengths = {len(word) for word in text.split()}
print("Unique word lengths:", word_lengths)
print("Sorted:", sorted(word_lengths))
Add a UUID Surrogate Key to Each Row in a CSV with Python
Generate a unique UUID string for every row in a CSV file using the standard-library uuid and csv modules.
import uuid
import csv
def add_surrogate_key(filename):
with open(filename, newline='') as f_in:
reader = csv.DictReader(f_in)
rows = list(reader)
for row in rows:
row['surrogate_key'] = str(uuid.uuid4())
with open(filename, 'w', newline='') as f_out:
writer = csv.DictWri…
How to Clean and Format Data in Python
This code loads JSON data, cleans records by removing empty fields and normalizing text, then summarizes the results with counts and unique keys.
import json
from pathlib import Path
def load_data(filepath: str) -> dict:
"""Load JSON data from a file."""
with Path(filepath).open("r", encoding="utf-8") as f:
return json.load(f)
def clean_records(records: list[dict]) -> list[dict]:
"""Remove empty fields and normalize text to lowercase."""…
Count Unique Contributors from Git Shortlog in Python
Parses git shortlog -sn output to count the number of unique contributors, handling duplicate entries and variable whitespace.
import subprocess
from collections import Counter
# Mock shortlog output as a list of lines (simulating git shortlog -sn output)
MOCK_SHORTLOG = """ 120 Alice Johnson
88 Bob Smith
45 Alice Johnson
30 Carol Williams
25 Bob Smith
10 Dave Brown
"""
def count_contributors_from_shortlog(text):
"…
How to Build a Chainable Filter Helper in Python
A beginner-friendly dataclass helper that chains filters, uniqueness, and slicing on any sequence, returning a plain list at the end.
from dataclasses import dataclass
from typing import Callable, Iterator, Sequence, TypeVar
T = TypeVar("T")
@dataclass
class FilterAssistant:
"""Beginner-friendly helper to filter any collection."""
data: Sequence[T]
def where(self, predicate: Callable[[T], bool]) -> "FilterAssistant":
return …
How to Use the pytest tmp_path Fixture for Temporary Directories
Use pytest's built-in tmp_path fixture to create a unique temporary directory per test for clean file I/O testing.
import pytest
def test_write_and_read_file(tmp_path):
# tmp_path is a pytest fixture that provides a temporary directory
# unique to each test invocation
data_file = tmp_path / "data.txt"
data_file.write_text("hello world")
assert data_file.read_text() == "hello world"
def test_multiple_tmp_pat…
How to Propagate X-Request-ID in Python
Generate a unique request ID when one is missing and pass it through API calls for distributed tracing.
import uuid
def generate_request_id() -> str:
"""Generate a unique request ID similar to X-Request-ID header."""
return str(uuid.uuid4())
def propagate_request_id(request_id: str | None) -> str:
"""Return the request ID for propagation, generating one if missing."""
if request_id:
return re…
How to deduplicate messages by ID in Python
Track seen message IDs in a set to skip duplicate messages and store unique content in a dict, with exact output showing which messages were added or skipped.
import time
class MessageStore:
def __init__(self):
self.seen_ids = set()
self.messages = {}
def add(self, message_id, content, timestamp=None):
timestamp = timestamp or time.time()
if message_id in self.seen_ids:
return False
self.seen_ids.add(message_…
How to Generate Experiment Tracking Run IDs in Python
Generate unique experiment run IDs with timestamps and random suffixes for tracking ML pipeline executions.
import random
import string
import time
def generate_run_id(prefix="exp"):
timestamp = time.strftime("%Y%m%d_%H%M%S")
suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
return f"{prefix}_{timestamp}_{suffix}"
if __name__ == "__main__":
# Simulate tracking three experiment r…
How to enforce a unique index constraint in Python
Mock a database unique index in Python that rejects duplicate rows based on one or more columns.
class MockIndex:
def __init__(self, columns):
self.columns = columns
self._values = set()
def insert(self, row):
key = tuple(row[col] for col in self.columns)
if key in self._values:
raise ValueError(f"Duplicate key {key} for columns {self.columns}")
self._v…
UUID vs sequential primary key in Python
Simulate and compare UUID vs sequential primary key generation in Python to understand trade-offs in ordering and uniqueness.
import uuid
import time
def create_record_with_uuid(name):
record_id = uuid.uuid4()
return {"id": record_id, "name": name}
def create_record_with_sequential_id(name, counter):
counter += 1
return {"id": counter, "name": name}
if __name__ == "__main__":
# Simulate users inserting records
sequ…
How to Salt Passwords per User in Python
Hash each user's password with a unique random salt using hashlib, and verify logins with timing-safe comparison.
import hashlib
import secrets
def hash_password(password: str, salt: str | None = None) -> tuple[str, str]:
"""Hash a password with a random salt (or provided salt).
Returns:
(salt_hex, password_hash_hex)
"""
if salt is None:
salt = secrets.token_hex(16)
salted = (salt + password)…
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.