Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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
Count how often each word appears in a string and list the unique words using Python dictionaries and sets.
def text_processor(text):
words = text.lower().split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
unique_words = set(words)
return word_count, unique_words
if __name__ == "__main__":
sample_text = "The quick brown fox jumps over the lazy dog and t…
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 Count Words and Find Common Words in Python with Dictionaries and Sets
Build a simple text processor that counts unique words with dictionaries and finds common words across text halves using sets.
def process_text(text):
"""Process text: count unique words with counts, find common words."""
words = text.lower().replace(",", "").replace(".", "").split()
word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1
total_words = len(words)
unique_wo…
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…
How to Validate Text and Count Words in Python
Count word frequencies, find unique and repeated words in a text using Python dictionaries and sets for beginner text validation.
def validate_text(text):
words = text.lower().split()
word_counts = {}
for word in words:
cleaned = word.strip('.,!?;:"\'')
if cleaned:
word_counts[cleaned] = word_counts.get(cleaned, 0) + 1
unique_words = set(word_counts.keys())
repeated_words = {word for word…
How to count words and find unique words in Python
Build a beginner-friendly text processor that counts word frequencies, finds unique words, and identifies words with vowels using dictionaries and sets.
def text_processor(text):
words = text.lower().replace(",", "").replace(".", "").split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
unique_words = set(words)
vowels = set("aeiou")
words_with_vowels = {word for word in unique_words if vowe…
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))
Text Processor with Dictionaries and Sets in Python
Build a simple text processor that counts word frequencies with a dictionary and tracks unique words with a set.
def analyze_text(text):
words = text.lower().split()
word_freq = {}
unique_words = set()
for word in words:
clean_word = word.strip('.,!?;:')
if clean_word:
word_freq[clean_word] = word_freq.get(clean_word, 0) + 1
unique_words.add(clean_word)
return…
Composition over Inheritance: How to Build a Wallet Account in Python
Demonstrates composition by wrapping a WalletAccount class in an AuditedWallet decorator-like class to add behavior without changing the original class.
class WalletAccount:
def __init__(self, owner, balance=0.0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
return self.balance
def withdraw(self, …
Group Data Helper Class in Python
A simple Python class that stores items under named groups, retrieves groups, items, and counts, and formats them as a readable summary.
class GroupData:
"""A simple helper class to store and group data for beginners."""
def __init__(self):
self.items = []
def add(self, item, group):
"""Add an item under a given group name."""
self.items.append({"item": item, "group": group})
def get_groups(self):
"""R…
How to Build a Data Helper Class in Python with OOP
Create a beginner-friendly Python class that loads CSV data, filters records by field, and counts entries using object-oriented programming.
class DataHelper:
"""A beginner-friendly OOP helper for handling simple datasets."""
def __init__(self, filename):
self.filename = filename
self.data = self._load_data()
def _load_data(self):
"""Load data from a CSV file into a list of dictionaries."""
import csv
…
How to Count Items in a Python Class
A beginner-friendly Inventory class that stores item quantities in a dictionary and provides add, remove, count, and summary methods.
class Inventory:
def __init__(self):
self.items = {}
def add(self, item, quantity=1):
self.items[item] = self.items.get(item, 0) + quantity
def remove(self, item, quantity=1):
if item not in self.items:
raise ValueError(f"{item} not in inventory")
self.items[it…
Bucket Numbers into Histogram Bin Counts in Python
Partition a list of numbers into equal-width histogram bins and count how many fall into each bin using only the Python standard library.
from collections import Counter
def histogram_bins(numbers, num_bins):
"""Bucket numbers into histogram bin counts."""
if not numbers:
return []
min_val = min(numbers)
max_val = max(numbers)
bin_width = (max_val - min_val) / num_bins
# Handle edge case where all values are id…
Count Smaller Elements to the Right in Python
Return a list where each index counts how many elements to its right are smaller than that element using a clean O(n²) nested-loop approach.
def count_smaller_elements(arr):
"""
Return a list where result[i] is the number of elements
to the right of arr[i] that are smaller than arr[i].
"""
result = []
for i in range(len(arr)):
count = 0
for j in range(i + 1, len(arr)):
if arr[j] < arr[i]:
…
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 Missing Numbers, Duplicates, and Ranges in Python
Analyze a list to identify missing numbers, duplicate values, and contiguous ranges using sets and the Counter class.
def find_missing_duplicates_ranges(numbers):
"""Find missing numbers, duplicates, and ranges in a list."""
from collections import Counter
if not numbers:
return {"missing": [], "duplicates": [], "ranges": []}
full_range = set(range(min(numbers), max(numbers) + 1))
present = set(n…
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} …
Game of Life Next State Grid in Python
Compute the next generation of Conway's Game of Life from a 2D grid using the standard three rules with neighbor counting.
def next_state(grid):
m, n = len(grid), len(grid[0])
new = [[0] * n for _ in range(m)]
for r in range(m):
for c in range(n):
total = 0
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
if dr == 0 and dc == 0:
continue
…
How to Count Distinct Elements in a List in Python
Count the number of unique items in a list by converting it to a set and returning its length.
def count_distinct_elements(items):
return len(set(items))
if __name__ == "__main__":
sample = [1, 2, 3, 2, 1, 4, 3, 5, 4, 6]
result = count_distinct_elements(sample)
print(result)
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.