Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Generate Initials from a Full Name in Python
Extract and uppercase the first letter of each word in a full name to produce initials using standard string methods.
def generate_initials(full_name):
parts = full_name.strip().split()
initials = ''.join(part[0].upper() for part in parts if part)
return initials
if __name__ == "__main__":
name = "john f. kennedy"
print(generate_initials(name))
How to Cycle Through a List Infinitely with itertools
This code uses itertools.cycle to create an infinite iterator over a list and returns the first n items from that cycle.
from itertools import cycle
def demonstrate_cycle(items, cycles=3):
"""
Cycle through a list infinitely using itertools.cycle.
Returns the first n items from the infinite cycle.
"""
cycled = cycle(items)
result = [next(cycled) for _ in range(len(items) * cycles)]
return result
if __name__…
How to Pipe Data Through a List of Transform Functions in Python
Applies a sequence of functions to an initial value using functools.reduce, creating a reusable pipe utility.
from functools import reduce
def pipe(data, *transforms):
return reduce(lambda value, func: func(value), transforms, data)
def double(x):
return x * 2
def add_one(x):
return x + 1
def to_string(x):
return f"Result: {x}"
if __name__ == "__main__":
initial = 5
result = pipe(initial, double, …
Build a defaultdict histogram of categories in Python
Count occurrences of each category in a list using collections.defaultdict(int) for automatic initialization.
from collections import defaultdict
def build_category_histogram(items):
"""Count occurrences of each category in a list of items."""
histogram = defaultdict(int)
for item in items:
histogram[item] += 1
return dict(histogram)
if __name__ == "__main__":
categories = ["fruit", "vegetable", …
How to Use defaultdict(list) to Group Words by First Letter in Python
This code groups a list of words by their first letter using a defaultdict with a list factory, then prints each group sorted by initial.
from collections import defaultdict
def group_by_initial(words):
groups = defaultdict(list)
for word in words:
groups[word[0].upper()].append(word)
return dict(groups)
if __name__ == "__main__":
words = ["apple", "banana", "apricot", "blueberry", "cherry"]
result = group_by_initial(words)…
Compute Derived Fields with @dataclass __post_init__ in Python
Compute derived fields like distance, area, and perimeter automatically in Python dataclasses using __post_init__ and field(init=False).
from dataclasses import dataclass, field
from math import sqrt
@dataclass
class Point:
x: float
y: float
distance: float = field(init=False)
def __post_init__(self):
self.distance = sqrt(self.x ** 2 + self.y ** 2)
@dataclass
class Rectangle:
width: float
height: float
area: flo…
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.
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
…
How to Define a Simple Class with __init__ and __repr__ in Python
Defines a Person class with __init__ to store name and age, and __repr__ to give a readable string representation.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name='{self.name}', age={self.age})"
if __name__ == "__main__":
p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
print(p1)
print(p2)
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.
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)
Validate dataclass fields with __post_init__ in Python
Add custom validation to a Python dataclass inside __post_init__, raising ValueError or TypeError for invalid field values.
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Product:
name: str
price: float
quantity: int = 1
category: Optional[str] = None
def __post_init__(self):
if not self.name or not isinstance(self.name, str):
raise ValueError("name must be a…
Cycle an iterable forever in Python
Define a generator that repeatedly yields items from an iterable, cycling back to the beginning infinitely.
def cycle_generator(iterable):
"""Yield items from iterable forever, cycling back to the start."""
items = list(iterable) # Convert to list so it can restart
index = 0
while True:
yield items[index]
index = (index + 1) % len(items)
if __name__ == "__main__":
colors = ["red", "gre…
Generator Function to Yield an Infinite Counter in Python
This code demonstrates a generator function that yields an infinite sequence of integers starting from a given value, allowing lazy, memory-efficient iteration.
def infinite_counter(start=0):
count = start
while True:
yield count
count += 1
if __name__ == "__main__":
counter = infinite_counter(5)
for _ in range(5):
print(next(counter))
How to Create an Infinite Arithmetic Sequence Generator in Python
Build a memory-efficient generator that yields an infinite arithmetic progression and extract the first N values with list comprehension.
"""Count generator infinite arithmetic progression"""
def arithmetic_counter(start=0, step=1):
"""Generate an infinite arithmetic sequence."""
current = start
while True:
yield current
current += step
if __name__ == "__main__":
counter = arithmetic_counter(1, 3)
result = [next(c…
How to Generate Fibonacci Numbers in Python Without Recursion
Build an efficient infinite Fibonacci sequence using a generator function with O(1) memory and no recursion overhead.
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
if __name__ == "__main__":
count = 10
result = list(fib(count))
print(result)
Take n items from an infinite Python generator
Uses itertools.islice to lazily take exactly n items from an infinite generator without exhausting it.
from itertools import islice
def count_up_from(start=0):
n = start
while True:
yield n
n += 1
def take_n(generator, count):
return list(islice(generator, count))
if __name__ == "__main__":
gen = count_up_from(10)
result = take_n(gen, 5)
print(result)
How to Generate a cloud-init User Data Mock in Python
Generate a cloud-init user data mock for a VM using a dataclass and JSON in Python.
import json
from dataclasses import dataclass, asdict
@dataclass
class VMConfig:
hostname: str
cpus: int
memory_mb: int
ssh_key: str
def generate_cloud_init_mock(config: VMConfig) -> str:
"""Build a cloud-init user-data mock for a VM."""
user_data = {
"hostname": config.hostname,
…
How to Initialize Sentry SDK with a Mock DSN in Python
Initialize the Sentry SDK in Python with a mock DSN to test error tracking without sending real events, then verify the DSN configuration.
import sentry_sdk
# Initialize Sentry SDK with a mock DSN (no real events will be sent)
sentry_sdk.init(
dsn="https://mock-public@mock-host/mock-project",
traces_sample_rate=1.0,
environment="development",
)
# Capture a test message to confirm SDK is configured
sentry_sdk.capture_message("Test message fr…
How to Build a Bloom Filter to Reduce Cache Misses in Python
Implement a probabilistic Bloom filter in Python that lets a cache quickly determine which keys are definitely not present, reducing expensive source lookups on cache misses.
import hashlib
import random
class BloomFilter:
def __init__(self, size=100, num_hashes=3):
self.size = size
self.num_hashes = num_hashes
self.bit_array = [0] * size
def _hashes(self, item):
result = []
for i in range(self.num_hashes):
hash_value = int(hash…
How to Mock a Slow Startup Probe in Python
Simulate slow service initialization with a configurable mock delay to test readiness probes.
import time
from dataclasses import dataclass, field
@dataclass
class StartupProbe:
name: str
min_wait_sec: float = 0.5
max_wait_sec: float = 2.0
_ready: bool = field(default=False, init=False, repr=False)
def initialize(self) -> None:
"""Simulate slow startup with a fixed mock delay."""…
How to Mock a UDAF Aggregate Function in Python
This code provides a minimal mock of a User-Defined Aggregate Function (UDAF), simulating the initialize-update-merge-finalize lifecycle with a defaultdict counter.
from collections import defaultdict
class MockUDAF:
"""A minimal mock of a User-Defined Aggregate Function.
Simulates aggregate lifecycle: initialize, update per row,
and finalize the result.
"""
def __init__(self):
self._buffer = defaultdict(int)
def initialize(self):
"""Re…
How to Build a Simple Binary Protocol Parser Mock in Python
Defines a mock binary protocol with field definitions, encoding, and decoding to simulate network packet parsing for A/B testing and experiment setup.
class SimpleProtocol:
def __init__(self, name, version):
self.name = name
self.version = version
self.fields = []
def add_field(self, field_name, field_size):
self.fields.append((field_name, field_size))
def parse(self, data):
if len(data) != sum(size for _, size i…
How to Perform Intent-to-Treat Analysis in Python
Runs an intent-to-treat analysis on mock A/B test data, comparing outcomes by initial group assignment with a t-test for significance.
import pandas as pd
import numpy as np
def intent_to_treat_analysis(data):
"""Perform intent-to-treat (ITT) analysis.
ITT compares outcomes based on initial treatment assignment,
regardless of whether participants actually received the treatment.
"""
# Create a copy to avoid mutating the origina…
How to Mock a Slow Startup Probe for Fast Testing in Python
This code shows how to replace a slow startup probe's initialization with a mock to make tests run fast and reliably.
import time
from unittest.mock import Mock, patch
class StartupProbe:
def __init__(self, init_time):
self.init_time = init_time
self.ready = False
def initialize(self):
time.sleep(self.init_time)
self.ready = True
return self.ready
def run_startup_probe(probe):
…
How to simulate a database migration init container mock in Python
A mock init container that runs environment checks and a staged database migration job before the main application starts, printing progress to stdout.
```python
class MigrationJob:
def __init__(self, name, steps):
self.name = name
self.steps = steps
self.current_step = 0
self.status = "pending"
def run(self):
print(f"Initializing migration job: {self.name}")
for step in self.steps:
self.current_ste…
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.