Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
Extract Email-Like Tokens from Text in Python
Uses a regular expression to find all email-like tokens in a string, returning them as a list with re.findall.
import re
def extract_email_like_tokens(text):
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b'
return re.findall(pattern, text)
if __name__ == "__main__":
sample_text = (
"Contact us at support@example.com or sales@company.co.uk. "
"Invalid: hello@world, user@.com, test@do…
Extract URLs from text with regex in Python
Uses a regular expression to find and print HTTP/HTTPS URLs from a block of text.
import re
text = """
Visit https://www.example.com for docs.
Contact support@mysite.org.
Check http://localhost:8000/api or ftp://files.example.net.
"""
url_pattern = r'https?://[^\s]+'
urls = re.findall(url_pattern, text)
for url in urls:
print(url)
How to Count Vowels in a String in Python
Counts uppercase and lowercase vowels in a given string using a set and a generator expression.
def count_vowels(text):
vowels = set("aeiouAEIOU")
return sum(1 for char in text if char in vowels)
if __name__ == "__main__":
sample = "Hello, World!"
result = count_vowels(sample)
print(f"Vowel count in '{sample}': {result}")
How to Extract Digits Only from a String in Python
This code uses a regular expression to remove all non-digit characters from a mixed string, returning only the digits.
import re
def extract_digits(text):
"""Return only the digits from the given text as a string."""
return re.sub(r'\D', '', text)
if __name__ == "__main__":
mixed = "abc123def456!@#789"
result = extract_digits(mixed)
print(result)
How to Mask Credit Card Middle Digits in Python
Mask the middle digits of credit card numbers in a string, keeping only the first 8 and last 4 digits, using regular expressions.
import re
def mask_credit_card(text: str) -> str:
pattern = re.compile(r'(\d{4}[-\s]?)(\d{4}[-\s]?)(\d{4}[-\s]?)(\d{4})')
return pattern.sub(lambda m: m.group(1) + m.group(2) + '****' + m.group(4), text)
if __name__ == "__main__":
sample = "Card: 1234-5678-9012-3456 and 1111 2222 3333 4444"
print(mas…
How to Remove HTML Tags in Python with Regex
Strips all HTML tags from a string using a regular expression and cleans extra whitespace.
import re
def remove_html_tags(text: str) -> str:
"""Remove all HTML tags from the given text using regex."""
# Remove opening and closing tags
clean = re.sub(r'<[^>]+>', '', text)
# Remove any extra whitespace left behind
clean = re.sub(r'\s+', ' ', clean).strip()
return clean
if __name__ ==…
How to Round Numbers with f-strings in Python
Round numbers directly inside f-string expressions using the built-in round() function for clean, readable output formatting.
def main():
# Values to format with expression-based rounding
price = 19.995
tax_rate = 0.0825
distance = 1234.56789
# Round inside the f-string expression using round()
print(f"Price rounded to cents: ${round(price, 2)}")
# Combine rounding with arithmetic inside the expression
total…
Check if List is Sorted Ascending in Python
Verify that a list is sorted in ascending order using the all() function and a generator expression.
def is_sorted_ascending(lst):
return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1))
if __name__ == "__main__":
test_lists = [
[1, 2, 3, 4, 5],
[1, 3, 2, 4, 5],
[5, 4, 3, 2, 1],
[1, 1, 2, 2, 3],
[10],
[]
]
for lst in test_lists:
print(f"{l…
Convert a List of Integers to a Comma-Separated String in Python
Convert a list of integers into a single comma-separated string using a generator expression and str.join.
def ints_to_comma_string(numbers):
return ",".join(str(num) for num in numbers)
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5]
result = ints_to_comma_string(numbers)
print(result)
How to Check if a List is Sorted in Descending Order in Python
This code defines a function that returns True if a given list is sorted in descending order, using a generator expression with all() to compare each adjacent pair.
def is_descending(lst):
"""Return True if list is sorted in descending order."""
return all(lst[i] >= lst[i + 1] for i in range(len(lst) - 1))
if __name__ == "__main__":
test_cases = [
[5, 4, 3, 2, 1],
[3, 3, 2, 1],
[1, 2, 3],
[10, 8, 9],
[]
]
for case in …
How to Use functools.reduce in Python
Apply functools.reduce with operator functions and lambda expressions to aggregate lists into sums, products, maximums, and concatenated strings.
from functools import reduce
import operator
# Sum all numbers in a list using reduce
numbers = [1, 2, 3, 4, 5]
sum_result = reduce(operator.add, numbers)
# Find the maximum value using reduce
max_result = reduce(lambda a, b: a if a > b else b, numbers)
# Multiply all numbers using reduce
product_result = reduce(la…
Normalize CSV Column Names to snake_case in Python
Convert CSV header names to snake_case using a regular expression and write the updated file in place.
import csv
import re
import sys
def to_snake_case(header):
header = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", header)
header = re.sub(r"[^a-zA-Z0-9]+", "_", header).strip("_").lower()
return header
def normalize_csv_headers(input_path, output_path=None):
with open(input_path, newline="", encoding="utf…
Count Word Frequency in Python with dict
Count how often each word appears in a text using Python's collections.Counter and regular expressions.
from collections import Counter
import re
def count_word_frequency(text):
"""Count frequency of each word in text (case-insensitive)."""
words = re.findall(r"\b\w+\b", text.lower())
return dict(Counter(words))
if __name__ == "__main__":
sample_text = "The quick brown fox jumps over the lazy dog. The …
How to Compute the Dot Product of Two Lists in Python
Compute the dot product of two equal-length numeric lists using a generator expression with zip and sum.
def dot_product(list1, list2):
"""
Compute the dot product of two numeric lists.
The lists must have the same length.
"""
if len(list1) != len(list2):
raise ValueError("Lists must have the same length")
return sum(a * b for a, b in zip(list1, list2))
if __name__ == "__main__":
…
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…
Count Data in Python with Comprehensions and Generators
Count list items with a dict comprehension and generate squares lazily with a generator expression, printing both results.
from collections import Counter
data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = {item: data.count(item) for item in set(data)}
square_gen = (x * x for x in range(5))
squares = list(square_gen)
if __name__ == "__main__":
print("Manual count:", counts)
print("Counter:", dict(Counter…
Generate Data with Python Comprehensions and Generators
Shows list, dict compregensions and generator expressions plus a Fibonacci generator to produce data lazily.
# Data generation helpers using comprehensions and generators
from itertools import islice
def fibonacci(limit):
"""Generate Fibonacci numbers up to a limit."""
a, b = 0, 1
while a <= limit:
yield a
a, b = b, a + b
def main():
# List comprehension: squares of even numbers
square…
How to Parse Data with Generators and Comprehensions in Python
This code demonstrates using a generator expression to filter active users and a dictionary comprehension to aggregate scores by name.
def parse_data_helper(raw_records):
"""Extract active users' names and scores from raw records."""
parsed = (
(record["name"], record["score"])
for record in raw_records
if record["active"] and record["score"] >= 0
)
return list(parsed)
def aggregate_scores(parsed_data):
"…
How to Split Data into Chunks and Use Generators in Python
Split a list into fixed-size chunks with a list comprehension and square even numbers lazily with a generator expression.
def split_numbers(data, chunk_size):
return [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]
def square_even_numbers(numbers):
return (n ** 2 for n in numbers if n % 2 == 0)
if __name__ == "__main__":
sample_data = list(range(1, 21))
chunks = split_numbers(sample_data, 5)
print…
How to Use Comprehensions and Generators in Python
Demonstrate list, set, and dictionary comprehensions plus generator expressions and generator functions in one beginner-friendly script.
def demonstrate_comprehensions_generators():
# List comprehension: transform and filter in one line
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [num ** 2 for num in numbers if num % 2 == 0]
print(f"Square of even numbers (list comprehension): {squares}")
# Set comprehension: unique values
…
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…
Merge Data with Comprehension and Generator in Python
Merge user and order data using a dictionary comprehension for lookups and a generator expression to filter and transform orders.
def merge_data(users, orders):
"""
Merge user and order data using a dictionary comprehension
and a generator expression for filtering.
"""
# Build a lookup: user_id -> user name
user_map = {user["id"]: user["name"] for user in users}
# Generator: yield orders with user names attached
…
Normalize Data in Python with Comprehensions and Generators
Clean a list by dropping None values with a comprehension, then min-max normalize it using a lazy generator expression — a beginner-friendly data preparation pattern.
import statistics
# Sample raw data including missing and outlier-ish values
raw = [22, 18, None, 25, 30, 19, 22, 17, None, 28, 24]
# Clean the data: drop None values using a list comprehension
clean = [x for x in raw if x is not None]
# Normalize using min-max scaling with a generator expression
min_val = min(clea…
Python Comprehensions and Generators for Beginners
Learn list, dict, and set comprehensions plus generator expressions and generator functions with clear, runnable examples.
# Demonstrates list comprehensions, dict comprehensions, set comprehensions, and generators
def demonstrate_comprehensions():
# List comprehension: squares of even numbers
numbers = range(1, 11)
even_squares = [n ** 2 for n in numbers if n % 2 == 0]
# Dict comprehension: number to its factorial
…
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.