Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Normalize a List of Numbers in Python
This Python function normalizes a list of numeric values to the range [0, 1] using min-max scaling, returning a new list and leaving the original unchanged.
def normalize(data):
"""
Normalize a list of numeric values to the range [0, 1].
Returns a new list, leaving the original unchanged.
"""
if not data:
return []
min_val = min(data)
max_val = max(data)
# Handle the edge case where all values are identical
if min_val …
How to Parse Bullet Points in Python
Extract bullet point items from raw text by splitting lines and filtering those that start with '- ' or '* '.
def parse_bullet_points(text):
"""Extract bullet point items from raw text."""
lines = text.splitlines()
items = []
for line in lines:
stripped = line.strip()
if stripped.startswith("- ") or stripped.startswith("* "):
item = stripped[2:]
if item:
…
How to Parse Delimited Data into a Python List
Splits a pipe-delimited string, strips whitespace, filters empty items, and returns a clean list with a loop.
def parse_data(raw_data):
"""Parse a pipe-delimited string into a list of cleaned items."""
items = raw_data.split("|")
parsed = []
for item in items:
cleaned = item.strip()
if cleaned:
parsed.append(cleaned)
return parsed
if __name__ == "__main__":
data = " apple…
How to Process Text Lines with Lists and Loops in Python
This code processes a list of text lines by stripping whitespace, converting to uppercase, and reporting character counts per line and totals.
def process_text(lines):
"""Convert a list of text lines to uppercase and report line statistics."""
processed = []
total_chars = 0
for index, line in enumerate(lines, start=1):
cleaned = line.strip().upper()
processed.append(cleaned)
total_chars += len(cleaned)
pri…
How to Process Text into Words in Python
Splits a string into words, strips punctuation, and returns a list of uppercase words using a loop.
def convert_text_processor(text):
words = text.split()
processed = []
for word in words:
clean = word.strip('.,!?;:')
if len(clean) > 0:
processed.append(clean.upper())
return processed
if __name__ == "__main__":
sample_text = "Hello, world! This is a Python e…
How to Process Text with Lists and Loops in Python
A beginner-friendly text processor that splits a sentence into words, filters by length, counts vowels, and reports results using lists and loops.
text = "Python makes text processing easy and fun"
words = text.lower().split()
print("Words in the sentence:")
for index, word in enumerate(words, start=1):
print(f"{index}. {word}")
filtered_words = [word for word in words if len(word) > 3]
print(f"\nWords longer than 3 characters: {filtered_words}")
letter…
How to Process Text with Lists and Loops in Python
Iterate over a list of text lines to count words, show uppercase versions, and report character counts per line.
# text_processor.py
def process_text(lines):
"""Count words, show uppercase, and count characters per line."""
total_words = 0
print("Line-by-line analysis:")
for i, line in enumerate(lines, start=1):
words = line.split()
total_words += len(words)
print(f" Line {i}: {len(words…
How to Reverse a List in Place Without Using reverse() in Python
A two-pointer while loop swaps elements from both ends toward the center to reverse a list in place without creating a copy.
def reverse_list_in_place(lst):
left = 0
right = len(lst) - 1
while left < right:
lst[left], lst[right] = lst[right], lst[left]
left += 1
right -= 1
if __name__ == "__main__":
my_list = [1, 2, 3, 4, 5]
print("Original:", my_list)
reverse_list_in_place(my_list)
prin…
How to Summarize a List of Numbers in Python
Loop over a list of numbers to compute total, count, average, min, and max, then return them in a dictionary.
def summarize_numbers(numbers):
"""Return a dict with basic stats for a list of numbers."""
total = 0
count = 0
smallest = numbers[0]
largest = numbers[0]
for num in numbers:
total += num
count += 1
if num < smallest:
smallest = num
if num > largest:…
How to Transpose a Matrix in Python (List of Lists)
Swap rows and columns of a 2D list using nested loops to produce a transposed matrix.
def transpose(matrix):
# Number of rows and columns in the original matrix
rows = len(matrix)
cols = len(matrix[0]) if rows > 0 else 0
# Create a new matrix with dimensions swapped
result = []
for j in range(cols):
new_row = []
for i in range(rows):
new_row.appe…
How to Validate List Data in Python
A beginner-friendly validation helper that checks if data is a list, enforces minimum length, and optionally verifies item types with clear error messages.
def validate_data(data, expected_types=None, min_length=1):
"""Validate that data is a non-empty list and optionally check item types."""
if not isinstance(data, list):
return False, f"Expected a list, got {type(data).__name__}"
if len(data) < min_length:
return False, f"List must have…
How to Validate Text Against Forbidden Words in Python
Checks whether a given text contains any forbidden words and returns a tuple with validity and offending words.
def validate_text(text, forbidden_words):
"""
Checks that text does not contain any forbidden words.
Returns (is_valid, offending_words) tuple.
"""
words = text.lower().split()
found = [word for word in words if word in forbidden_words]
return len(found) == 0, found
if __name__ == "__main…
How to check list items by type and emptiness in Python
Loop through a list with enumerate(), classify each item as empty, number, or text, and print a formatted status for each element.
def check_data(data):
"""Check each item in a list and print whether it's valid."""
for i, item in enumerate(data):
if item is None or item == "":
status = "empty"
elif isinstance(item, (int, float)):
status = "number"
else:
status = "text"
pr…
How to summarize and transform lists in Python
Compute count, sum, min, max, and average for a list and multiply each element by a factor using simple loops and built-in functions.
def summarize(data):
"""Return a summary of a list: count, sum, min, max, average."""
count = len(data)
total = sum(data)
minimum = min(data)
maximum = max(data)
average = total / count if count else 0
return count, total, minimum, maximum, average
def multiply_elements(data, factor=2):
…
How to unzip a list of pairs into two lists in Python
Split a list of (a, b) tuples into two separate lists by iterating with a for loop and appending each element to its own output list.
def unzip(pairs):
"""Split a list of (a, b) pairs into two separate lists."""
if not pairs:
return [], []
firsts = []
seconds = []
for a, b in pairs:
firsts.append(a)
seconds.append(b)
return firsts, seconds
if __name__ == "__main__":
pairs = [(1, 'a'), (…
Pairwise Adjacent Differences in a Python List
Computes the absolute differences between each pair of adjacent elements in a list using a concise list comprehension.
def adjacent_differences(nums):
"""Return list of absolute differences between adjacent elements."""
return [abs(nums[i] - nums[i + 1]) for i in range(len(nums) - 1)]
if __name__ == "__main__":
sample = [3, 7, 2, 9, 5]
diffs = adjacent_differences(sample)
print("Original list:", sample)
print…
Round Robin Merge Multiple Lists in Python
Merge multiple lists by taking one element from each in turn, stopping when all lists are exhausted.
from itertools import cycle
def round_robin_merge(*lists):
"""Merge multiple lists by taking one element from each in turn."""
result = []
max_len = max(len(lst) for lst in lists)
for i in range(max_len):
for lst in lists:
if i < len(lst):
result.append(lst[i])…
Separate Evens and Odds into Two Lists in Python
Split a list of numbers into two lists containing even and odd numbers using a simple loop and the modulo operator.
def separate_evens_odds(numbers):
evens = []
odds = []
for num in numbers:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return evens, odds
if __name__ == "__main__":
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens, odds = separate_evens_odds(nu…
Benchmark list append vs comprehension in Python
This micro-benchmark compares the speed of building a list with a for loop and append versus a list comprehension, using the timeit module to get precise timings.
import timeit
# Build a list of the first 1,000,000 integers using append in a loop
def append_loop(n=1_000_000):
result = []
for i in range(n):
result.append(i)
return result
# Build the same list using a list comprehension
def comprehension(n=1_000_000):
return [i for i in range(n)]
if __n…
Build a Progress Callback Function for Loops in Python
Create a reusable progress callback that receives per-step data and lets callers log or update a UI as a loop runs.
def run_with_progress(items, desc="Processing", step_callback=None):
"""Run a loop with progress updates via callback."""
total = len(items)
for idx, item in enumerate(items):
# Process the item (simulated work here)
result = item * 2
# Build progress data dictionary
if ste…
How to Count Items with Default Parameters in Python
Define a Python function that prints each item with a running counter, using default parameters to allow custom start values and step increments.
def count_items(items, start=0, step=1):
"""Count items in a list with configurable start value and step."""
count = start
for item in items:
print(f"{count}: {item}")
count += step
if __name__ == "__main__":
fruits = ["apple", "banana", "cherry"]
print("Default parameters (start=0…
How to Create an Iterator Class with Dunder Methods in Python
A minimal Counter class implementing __iter__ and __next__ to act as a self-iterating iterator, yielding numbers from start to end-1.
class Counter:
def __init__(self, start=0, end=5):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
value = self.current
self.current += 1
return val…
How to Implement a Trampoline for Tail Recursion in Python
This code implements a trampoline decorator that converts tail-recursive functions into iterative loops, allowing deep recursion without hitting Python's recursion limit.
def trampoline(fn):
"""Convert a tail-recursive function into an iterative loop."""
def wrapper(*args, **kwargs):
result = fn(*args, **kwargs)
while callable(result):
result = result()
return result
return wrapper
@trampoline
def factorial(n, acc=1):
"""Tail-recursi…
Compound interest calculator in Python
Compute future investment value with the compound interest formula and a readable year-by-year loop.
def future_value(
principal: float,
annual_rate: float,
years: int,
compounds_per_year: int = 12,
) -> float:
"""Return balance after compound interest (rounded to cents)."""
rate_per_period = annual_rate / compounds_per_year
periods = compounds_per_year * years
amount = principal * (1 …
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.