Tuesday, December 1, 2026
5 snippets
1. Count words with Counter
Counter turns a list of words into a tally in one line, and most_common() gives the top results. I reach for it whenever I need frequencies.
from collections import Counter text = "the quick brown fox jumps over the lazy dog the end" counts = Counter(text.split()) print(counts.most_common(3))
[('the', 3), ('quick', 1), ('brown', 1)]Line by line
- 1Imports
Counterfrom thecollectionsmodule. - 3Stores the text
'the quick brown fox jumps over the l...intext. - 4Stores a count of how many times each item appears in text.split() in
counts. - 5Prints
counts.most_common(3)to the screen.
2. Flatten a nested list with yield from
A generator that calls itself with yield from can walk lists of any depth without building temporary lists.
def flatten(items):
for item in items:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
print(list(flatten([1, [2, [3, 4]], 5, [[6]]])))[1, 2, 3, 4, 5, 6]
Line by line
- 1Defines a function named
flattenthat takesitems. The indented lines below are what it does when called. - 2Loops over
items, putting each item intoitemin turn and running the indented lines below once for each. - 3Checks whether
isinstance(item, list)is true. If it is, the indented lines below run; if not, Python skips them. - 4Hands
flatten(item)back to whoever is looping, then pauses here until asked for the next one. - 5Otherwise, when none of the checks above were true, the indented lines below run.
- 6Hands
itemback to whoever is looping, then pauses here until asked for the next one. - 9Prints
list(flatten([1, [2, [3, 4]], 5, [[6]]]))to the screen.
3. Merge dictionaries with the | operator
Since Python 3.9, a | b builds a new dictionary where the right-hand side wins on duplicate keys, which is perfect for defaults plus user settings.
defaults = {"theme": "dark", "font": 14}
user = {"font": 18, "lang": "en"}
settings = defaults | user
print(settings){'theme': 'dark', 'font': 18, 'lang': 'en'}Line by line
- 1Stores a dictionary with 2 entries in
defaults. - 2Stores a dictionary with 2 entries in
user. - 4Stores the result of
defaults | userinsettings. - 5Prints
settingsto the screen.
4. Fibonacci with a cache
Plain recursive Fibonacci repeats the same work again and again. @cache remembers each answer, so even fib(60) is instant.
from functools import cache
@cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print([fib(i) for i in range(10)])
print(fib(60))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] 1548008755920
Line by line
- 1Imports
cachefrom thefunctoolsmodule. - 4-5Defines a function named
fibthat takesn. It is wrapped by the decoratorcache. The indented lines below are what it does when called. - 6Sends
n if n < 2 else fib(n - 1) + fib(n - 2)back to the caller and ends the function. - 9Prints
[fib(i) for i in range(10)]to the screen. - 10Prints
fib(60)to the screen.
5. Check for a palindrome
Keep only letters and digits, lower-case them, then compare the list with its reverse using the slice [::-1].
def is_palindrome(text):
cleaned = [c.lower() for c in text if c.isalnum()]
return cleaned == cleaned[::-1]
for phrase in ["Never odd or even", "Python"]:
print(phrase, "->", is_palindrome(phrase))Never odd or even -> True Python -> False
Line by line
- 1Defines a function named
is_palindromethat takestext. The indented lines below are what it does when called. - 2Stores a new list built with a list comprehension in
cleaned. - 3Sends
cleaned == cleaned[::-1]back to the caller and ends the function. - 6Loops over
['Never odd or even', 'Python'], putting each item intophrasein turn and running the indented lines below once for each. - 7Prints
phrase,'->',is_palindrome(phrase)to the screen.