Home › Python Code of the Day
Fresh snippets, newest day first

🗓️ Python Code
of the Day

I write this page for the days when you only have ten minutes. Each day I add a small set of two to five short Python snippets, newest day first. Every snippet is complete, runs in your browser with the Run button, and comes with a plain-English note about the idea it shows.

🐍 Write and Run Python Here

Type Python below and press Run. It runs inside the browser, so there is nothing to install.

Output

Press Run to see the output here.

Works with numpy, pandas, matplotlib and more; they load when you import them. Tap Stop if a program never ends.

Ten minutes, a few snippets

Read the note first, guess what the code prints, then press Run to check it. After that, change something small: a number, a string, a condition. Breaking a snippet on purpose and reading the error teaches more than copying it ever will.

Snippets here are deliberately short. When a topic deserves more room, I link it to the full lessons in the curriculum. If you want a gentler start, begin with the beginner modules and come back for the daily practice.

💡

Run buttons load a small Python engine in your browser the first time (about 10–20 seconds). Nothing is sent to a server, and the code never leaves the device.

Archive

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.

python
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))
Expected output
[('the', 3), ('quick', 1), ('brown', 1)]

Line by line

  1. 1Imports Counter from the collections module.
  2. 3Stores the text 'the quick brown fox jumps over the l... in text.
  3. 4Stores a count of how many times each item appears in text.split() in counts.
  4. 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.

python
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]]])))
Expected output
[1, 2, 3, 4, 5, 6]

Line by line

  1. 1Defines a function named flatten that takes items. The indented lines below are what it does when called.
  2. 2Loops over items, putting each item into item in turn and running the indented lines below once for each.
  3. 3Checks whether isinstance(item, list) is true. If it is, the indented lines below run; if not, Python skips them.
  4. 4Hands flatten(item) back to whoever is looping, then pauses here until asked for the next one.
  5. 5Otherwise, when none of the checks above were true, the indented lines below run.
  6. 6Hands item back to whoever is looping, then pauses here until asked for the next one.
  7. 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.

python
defaults = {"theme": "dark", "font": 14}
user = {"font": 18, "lang": "en"}

settings = defaults | user
print(settings)
Expected output
{'theme': 'dark', 'font': 18, 'lang': 'en'}

Line by line

  1. 1Stores a dictionary with 2 entries in defaults.
  2. 2Stores a dictionary with 2 entries in user.
  3. 4Stores the result of defaults | user in settings.
  4. 5Prints settings to 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.

python
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))
Expected output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
1548008755920

Line by line

  1. 1Imports cache from the functools module.
  2. 4-5Defines a function named fib that takes n. It is wrapped by the decorator cache. The indented lines below are what it does when called.
  3. 6Sends n if n < 2 else fib(n - 1) + fib(n - 2) back to the caller and ends the function.
  4. 9Prints [fib(i) for i in range(10)] to the screen.
  5. 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].

python
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))
Expected output
Never odd or even -> True
Python -> False

Line by line

  1. 1Defines a function named is_palindrome that takes text. The indented lines below are what it does when called.
  2. 2Stores a new list built with a list comprehension in cleaned.
  3. 3Sends cleaned == cleaned[::-1] back to the caller and ends the function.
  4. 6Loops over ['Never odd or even', 'Python'], putting each item into phrase in turn and running the indented lines below once for each.
  5. 7Prints phrase, '->', is_palindrome(phrase) to the screen.

Monday, November 30, 2026

2 snippets

1. Swap two variables without a temp

Python evaluates the right side first, builds a tuple, then unpacks it. That is why a, b = b, a swaps cleanly.

python
a, b = 3, 7
a, b = b, a
print(a, b)
Expected output
7 3

Line by line

  1. 1Assigns several names at once: a gets 3, b gets 7. Python works out the right side first, so this also swaps values safely.
  2. 2Assigns several names at once: a gets b, b gets a. Python works out the right side first, so this also swaps values safely.
  3. 3Prints a, b to the screen.

2. enumerate with a custom start

enumerate(items, start=1) gives human-friendly numbering without a manual counter variable.

python
fruits = ["apple", "banana", "cherry"]
for number, fruit in enumerate(fruits, start=1):
    print(number, fruit)
Expected output
1 apple
2 banana
3 cherry

Line by line

  1. 1Stores a list of 3 items in fruits.
  2. 2Loops over enumerate(fruits, start=1), putting each item into (number, fruit) in turn and running the indented lines below once for each.
  3. 3Prints number, fruit to the screen.