Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
Count Characters, Words, and Lines in Python Text
Counts characters, words, lines, and the most common words in a given string using Python's standard library.
from collections import Counter
def count_data(text):
"""Count characters, words, lines, and most common words in text."""
char_count = len(text)
word_count = len(text.split())
line_count = text.count("\n") + 1
word_freq = Counter(text.lower().split())
most_common = word_freq.most_common(3)
…
Find Most Active Contributors in a Repository with Python
Filter recent commits by date and count the most active contributors using Counter and datetime.
from collections import Counter
from datetime import datetime, timedelta
# Simulated commit data
commits = [
{"author": "Alice", "timestamp": datetime.now() - timedelta(days=1)},
{"author": "Bob", "timestamp": datetime.now() - timedelta(days=2)},
{"author": "Alice", "timestamp": datetime.now() - timedelta…
How to Build a Frequency Map from a List in Python
This code builds a dictionary that maps each unique element in a list to its count using the Counter class from the collections module.
from collections import Counter
def build_frequency_map(values):
"""Return a dictionary mapping each unique value to its frequency."""
return dict(Counter(values))
if __name__ == "__main__":
data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
freq_map = build_frequency_map(data)
prin…
How to Count Occurrences of a Value in a Python List
Counts how many times a specific value appears in a list using a simple loop and a counter variable.
def count_occurrences(data, target):
count = 0
for item in data:
if item == target:
count += 1
return count
if __name__ == "__main__":
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
target_value = 5
result = count_occurrences(numbers, target_value)
print(f"The value {targ…
How to Find the Mode in a Python List
Find the most frequent value (mode) in a Python list using the collections.Counter class, handling empty lists and ties.
from collections import Counter
def find_mode(numbers):
if not numbers:
return None
counts = Counter(numbers)
max_count = max(counts.values())
modes = [num for num, count in counts.items() if count == max_count]
return modes[0] if len(modes) == 1 else modes
if __name__ == "__main__":
…
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 a Timing Decorator in Python
A Python decorator that measures and prints the execution time of any function using time.perf_counter.
import time
from functools import wraps
def timing_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
elapsed = end - start
print(f"{func.__name__} took {elapsed:.6f} seconds"…
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 Extract IP Address Counts from Access Logs in Python
Read a web server access log, count occurrences of each IP address using regex and Counter, and print the ranked results.
import re
from collections import Counter
from pathlib import Path
def extract_ip_counts(log_file_path):
ip_pattern = r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
ip_counter = Counter()
with open(log_file_path, 'r') as file:
for line in file:
match = re.match(ip_pattern, line)
…
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 …
Count word frequency in Python with dict and Counter
Count how often each word appears in a string using Counter, converted to a plain dict, and print results alphabetically.
from collections import Counter
import re
def count_word_frequency(text):
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 dog barks, and the fox runs."
frequency = count_word_frequency(…
How to Convert a Counter to a Plain Dict with Sorted Items in Python
This code converts a collections.Counter into a regular dictionary with items sorted by key, useful for stable, readable output.
from collections import Counter
def counter_to_sorted_dict(counter):
"""Convert a Counter to a plain dict with sorted items."""
return dict(sorted(counter.items()))
if __name__ == "__main__":
# Example usage
data = Counter(['apple', 'banana', 'apple', 'cherry', 'banana', 'date', 'apple'])
print("…
How to Count Co-occurrence Pairs in Python with Nested Dictionaries
This code counts how often any two items appear together in the same group, using a nested defaultdict keyed by item pairs.
from itertools import combinations
from collections import defaultdict
def count_cooccurrences(items_per_group):
cooccurrence = defaultdict(lambda: defaultdict(int))
for group in items_per_group:
for a, b in combinations(sorted(group), 2):
cooccurrence[a][b] += 1
cooccurrence[b…
How to Count Elements and Find Duplicates in a Python List
Count occurrences of each element in a list, extract unique values, and identify duplicates using Python dictionaries and sets.
def analyze_counts(data):
"""Count elements, return unique values, and find duplicates."""
# Count occurrences using a dictionary
counts = {}
for item in data:
counts[item] = counts.get(item, 0) + 1
# Alternative compact approach with set
unique_items = set(data)
# Fi…
How to Count Tags with Sets and Dictionaries in Python
Count tag frequencies and collect unique tags from a list of dictionaries using Counter and sets in Python.
from collections import Counter
import json
def count_tags(entries):
"""Count tag frequencies across a list of entry dicts, using sets/dicts."""
tag_counter = Counter()
all_tags = set()
for entry in entries:
tags = set(entry["tags"])
all_tags.update(tags)
tag_counter.update(ta…
How to Count Word Frequencies in Python with Counter and Sets
This code processes a text string by lowercasing, splitting into words, counting frequencies with Counter, and extracting unique and sorted word lists using sets.
from collections import Counter
def process_text(text):
words = text.lower().split()
word_counts = Counter(words)
unique_words = set(words)
sorted_words = sorted(unique_words)
return {
"total_words": len(words),
"unique_words": len(unique_words),
"word_frequencies": di…
How to Subtract Counters in Python for Bag Differences
Use the Counter class's subtraction operator to compute bag differences, removing items and counts that appear in one multiset but not the other.
from collections import Counter
def subtract_counters(bag1, bag2):
"""Return the difference of two Counters (bag1 - bag2)."""
return bag1 - bag2
if __name__ == "__main__":
inventory = Counter(apples=10, bananas=5, oranges=3)
sold = Counter(apples=4, bananas=2, grapes=2)
remaining = subtract_count…
How to Use Counter for Most Common Elements in Python
This code demonstrates how to find the most frequent elements in a list using Python's Counter class from the collections module.
from collections import Counter
def most_common_elements(items, n=1):
"""Return the n most common elements and their counts."""
counter = Counter(items)
return counter.most_common(n)
if __name__ == "__main__":
data = ["apple", "banana", "apple", "orange", "banana", "apple", "grape"]
print(most_co…
How to Use Dictionaries and Sets in Python for Beginners
Introduces Python dictionaries and sets with practical examples including creating, modifying, and performing set operations, plus a word-frequency counter.
def demonstrate_dict_sets():
# Create a dictionary with basic info
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print("Dictionary:", person)
# Access and modify dictionary values
person["age"] = 31
person["email"] = "alice@example.com"
print("Afte…
Multiset with Counter update and elements in Python
Demonstrates using collections.Counter as a multiset: updating counts with update() and iterating elements() to get repeated items.
from collections import Counter
multiset = Counter(['apple', 'banana', 'apple'])
multiset.update(['banana', 'cherry', 'apple'])
print("Elements after update:", sorted(multiset.elements()))
print("Counts:", dict(multiset))
print("Most common:", multiset.most_common(2))
Find Common Elements in List of Lists in Python
Return elements that appear in every sublist of a nested list, preserving duplicates with Counter intersection.
from collections import Counter
def common_elements(list_of_lists):
"""Return elements present in every sublist."""
if not list_of_lists:
return []
counts = Counter(list_of_lists[0])
for sublist in list_of_lists[1:]:
counts &= Counter(sublist)
return list(counts.elements())
if _…
Find Elements Appearing More Than n/3 Times in Python
Return all elements that occur more than len(array)/3 times using a simple dictionary counter.
def majority_third(arr):
"""Return elements appearing more than len(arr)/3 times."""
cutoff = len(arr) / 3
counts = {}
for x in arr:
counts[x] = counts.get(x, 0) + 1
return [x for x, c in counts.items() if c > cutoff]
if __name__ == "__main__":
test1 = [3, 2, 3]
test2 = [1, 1, 1, …
Find Single Number Appearing Once in Python
Count frequency of each number in a list and return the one that appears exactly once when all others appear twice.
from collections import Counter
def find_single_number(nums):
counts = Counter(nums)
for num, count in counts.items():
if count == 1:
return num
return None
if __name__ == "__main__":
nums = [4, 1, 2, 1, 2]
result = find_single_number(nums)
print(f"Single number in {nums} …
How to Count Occurrences of Each Value in Python
Count how many times each value appears in a list using Python's Counter from the collections module.
from collections import Counter
def count_occurrences(values):
"""Return a dictionary mapping each value to its count."""
return dict(Counter(values))
if __name__ == "__main__":
sample_data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
result = count_occurrences(sample_data)
print(r…
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.