Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Filter Empty Strings in Python
Remove empty and whitespace-only strings from a list using a list comprehension with the strip() method.
def filter_empty_strings(strings):
"""
Filter out empty strings (including whitespace-only strings)
from a list of strings.
"""
return [s for s in strings if s.strip()]
if __name__ == "__main__":
sample_list = ["hello", "", "world", " ", "python", " ", "!"]
filtered = filter_empty_strin…
How to Filter None Values from a Mixed List in Python
Filter None values from a mixed Python list using a list comprehension with the `is not None` condition.
mixed_list = [1, None, "hello", None, 3.14, None, [1, 2], None]
filtered_list = [item for item in mixed_list if item is not None]
print(f"Original list: {mixed_list}")
print(f"Filtered list: {filtered_list}")
print(f"Original length: {len(mixed_list)}, Filtered length: {len(filtered_list)}")
How to Parse a Comma String into a List of Integers in Python
Converts a comma-separated string into a list of integers, handling spaces and empty inputs.
def parse_csv_to_ints(text: str) -> list[int]:
"""Parse a comma-separated string into a list of integers."""
if not text.strip():
return []
return [int(part.strip()) for part in text.split(",") if part.strip()]
if __name__ == "__main__":
sample = "10, 20, 30, 40, 50"
result = parse_csv_to_…
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…
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…
Replace Negative Values in a List with Python
This code defines a function that replaces every negative number in a list with a replacement value, defaulting to zero, using a list comprehension.
def replace_if_negative(values, replacement=0):
return [replacement if value < 0 else value for value in values]
if __name__ == "__main__":
numbers = [5, -3, 8, -1, 0, -7, 2]
result = replace_if_negative(numbers)
print(f"Original: {numbers}")
print(f"Replaced: {result}")
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…
Python Filter Function with Default Parameters for Beginners
Create a reusable filter function with default parameters to keep or exclude numbers above or below a threshold.
def filter_numbers(numbers, threshold=0, reverse=False):
"""Return numbers that pass the threshold filter.
Args:
numbers: list of numbers to filter
threshold: minimum value to keep (default 0)
reverse: if True, keep numbers below threshold (default False)
"""
if reverse:
…
How to Normalize Data in Python with Dictionaries and Sets
Normalize a list of dicts by keeping selected keys, stripping/lowercasing strings, and extracting unique sorted values using set comprehension.
def normalize_data(data, keys):
"""
Normalize a list of dictionaries by keeping only specified keys
and converting values to proper types.
"""
normalized = []
for item in data:
clean_item = {}
for key in keys:
value = item.get(key)
if isinstance(value, st…
How to Validate Required Dict Keys in Python
Check whether a dictionary contains all required keys and return the list of missing ones using a simple list comprehension.
def find_missing_keys(data: dict, required_keys: list) -> list:
"""Return a list of required keys that are missing from the dictionary."""
return [key for key in required_keys if key not in data]
if __name__ == "__main__":
user_data = {
"name": "Alice",
"email": "alice@example.com",
…
How to Create a Data Splitter Class in Python
This code defines a DataSplitter class that splits data by index, into chunks, or by a predicate, demonstrating OOP principles in Python.
class DataSplitter:
def __init__(self, data):
self.data = list(data)
def split_by_index(self, index):
return self.data[:index], self.data[index:]
def split_into_chunks(self, chunk_size):
return [self.data[i:i + chunk_size] for i in range(0, len(self.data), chunk_size)]
…
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.
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"}
…
How to Add Two Lists Elementwise in Python
Add two equal-length lists element by element using a list comprehension with zip, returning a new list of summed values.
def elementwise_add(list1, list2):
return [a + b for a, b in zip(list1, list2)]
if __name__ == "__main__":
list_a = [1, 2, 3, 4]
list_b = [10, 20, 30, 40]
result = elementwise_add(list_a, list_b)
print(result)
How to Apply a Function to Sliding Window Slices in Python
This Python code applies a given function to every contiguous window of a specified size in a list, returning a list of results.
def apply_to_sliding_windows(data, window_size, func):
return [func(data[i:i + window_size]) for i in range(len(data) - window_size + 1)]
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5, 6]
window_size = 3
results = apply_to_sliding_windows(numbers, window_size, sum)
print(results)
results…
How to Combine filter and map with a List Comprehension in Python
This Python code demonstrates how to combine filtering and mapping in a single list comprehension and shows the equivalent filter() and map() approach.
def square(x):
return x * x
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
result = [square(x) for x in numbers if is_even(x)]
print(f"Original numbers: {numbers}")
print(f"Squares of even numbers: {result}")
# Combined filter + map equivalent
filtered = filter(is_even, numbers)
mapp…
How to Compare Two Lists Elementwise for Greater Flags in Python
Compare two equal-length lists element by element and return a list of booleans marking where list_a values are greater than list_b values.
def compare_lists_greater(list_a, list_b):
"""
Compare two lists elementwise and return a list of booleans
indicating whether each element in list_a is greater than the
corresponding element in list_b.
"""
if len(list_a) != len(list_b):
raise ValueError("Lists must have the same length"…
How to Generate an Arithmetic Progression List in Python
Generates a list of terms in an arithmetic progression using a list comprehension.
def generate_ap(start, difference, count):
"""Generate a list of n terms in an arithmetic progression."""
return [start + i * difference for i in range(count)]
if __name__ == "__main__":
ap = generate_ap(3, 5, 6)
print(ap)
How to Replace Outliers Beyond Threshold with Cap in Python
Replace values that fall below a lower threshold or above an upper threshold by capping them to the threshold values using a simple Python function.
def replace_outliers_with_cap(data, lower_threshold=None, upper_threshold=None):
"""Replace values beyond given thresholds with the threshold values (capping)."""
if lower_threshold is None and upper_threshold is None:
raise ValueError("At least one threshold must be provided.")
capped_data = …
Convert Data in Python with Comprehensions and Generators
Convert mixed data to integers, filter and transform numbers, and extract fields from dicts using list comprehensions and generator expressions.
def convert_numbers(data):
"""Convert a list of mixed values into integers using a comprehension."""
return [int(item) for item in data if item is not None]
def double_even_numbers(numbers):
"""Double only even numbers using a generator expression."""
return (n * 2 for n in numbers if n % 2 == 0)
d…
How to Sort Data with Comprehensions and Generators in Python
Sort a list of tuples by a key, then use a list comprehension to extract names and a generator to square high ranks.
data = [("Anna", 3), ("Ben", 1), ("Clara", 2), ("Dan", 5), ("Eve", 4)]
# Comprehension: list of tuples (name, rank) sorted ascending by rank
sorted_by_rank = sorted(data, key=lambda x: x[1])
# Comprehension: extract just the names in rank order
names_in_rank_order = [name for name, rank in sorted_by_rank]
# Generat…
How to Use List Comprehensions and Generators in Python
Analyze a list of numbers using a list comprehension to square evens, a generator for sum, and a generator expression for the maximum squared value.
def analyze_numbers(numbers):
squared = [n ** 2 for n in numbers if n % 2 == 0]
total = sum(n for n in numbers)
max_squared = max((n ** 2 for n in numbers), default=0)
return squared, total, max_squared
if __name__ == "__main__":
data = [1, 2, 3, 4, 5, 6]
evens_squared, total_sum, max_sq = an…
How to Use List Comprehensions and Generators to Transform Data in Python
Transform a list of integers by squaring even numbers with a list comprehension and cubing odd numbers with a generator.
def transform_data(data):
"""
Transform a list of integers:
- squares of even numbers using a list comprehension
- cubes of odd numbers using a generator
"""
squares = [num ** 2 for num in data if num % 2 == 0]
cubes = (num ** 3 for num in data if num % 2 != 0)
return squares, cubes
i…
How to Filter Data in Python
Filter a list of dictionaries by exact key-value matches or numerical ranges using concise list comprehensions.
from typing import List, Dict, Any
def filter_data(
data: List[Dict[str, Any]], key: str, value: Any
) -> List[Dict[str, Any]]:
"""Return records where data[key] equals value."""
return [record for record in data if record.get(key) == value]
def filter_by_range(
data: List[Dict[str, Any]], key: str…
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.