Coding Tricks

15 Python Tricks for Beginners (We Ran Every One on 3.12)

Most beginner Python code works. It’s just longer than it needs to be, and that’s the gap these Python tricks for beginners close.

You write a counter loop with i = 0 and i += 1, a dictionary of lists with three if key not in d checks, and a print statement that spells out every variable name twice. None of that is wrong. But Python ships with small features that do those jobs in one line, and a lot of them landed in the last few releases, so older tutorials never mention them.

Below are 15 of them. We ran every snippet on Python 3.12.4 and pasted the real output under each one. Where a trick needs a recent version, we say which, so you don’t get a confusing syntax error on an old install.

Python f-string tricks for printing and formatting

1. Debug prints with f”{x=}”

Add an equals sign inside the braces and Python prints the expression and its value. It’s been there since 3.8 and still surprises people.

user = "sara"
score = 42
print(f"{user=} {score=}")
print(f"{score * 2 = }")

# user='sara' score=42
# score * 2 = 84

Spaces around the = are kept in the output, which makes longer expressions easier to read.

Common mistake: leaving these prints in the finished code. They’re for a quick look while you work. Anything you want to keep should go through the logging module, so you can switch messages off later without hunting down every print().

2. Number formatting without a library

price = 1234567.891
print(f"{price:,.2f}")   # 1,234,567.89
print(f"{0.0734:.1%}")   # 7.3%
print(f"{7:03d}")        # 007

Thousands separators, percentages and zero padding. The full mini-language is in the format spec docs, and it’s worth bookmarking.

3. Same quotes inside an f-string (new in Python 3.12)

Before 3.12 this line was a syntax error, because the inner double quotes ended the string early. PEP 701 fixed it.

song = {"title": "Numb", "artist": "Linkin Park"}
print(f"Now playing: {song["title"]} by {song["artist"]}")

# Now playing: Numb by Linkin Park

Handy, but if your code also has to run on 3.11 or older, stick to single quotes inside.

Python shortcuts for loops

4. enumerate() with a start number

names = ["Ali", "Bea", "Cy"]
for i, name in enumerate(names, start=1):
    print(i, name)

# 1 Ali
# 2 Bea
# 3 Cy

No manual counter, and start=1 gives you human-friendly numbering for menus or reports.

When not to use it: if the only reason you want the index is to read a second list at the same position (ages[i]), you want zip() instead. That’s the next trick. The habit worth dropping completely is for i in range(len(names)).

5. zip(…, strict=True)

Plain zip() stops at the shortest list and says nothing. That silent cut is a classic source of missing rows. Since 3.10 you can ask it to complain instead.

names = ["Ali", "Bea", "Cy"]
ages = [31, 27]
print(list(zip(names, ages)))
# [('Ali', 31), ('Bea', 27)]   <- Cy vanished

list(zip(names, ages, strict=True))
# ValueError: zip() argument 2 is shorter than argument 1

6. Chunk a list with itertools.batched (3.12+)

Splitting a list into groups of N used to mean a slicing loop or a recipe copied from Stack Overflow. Python 3.12 added batched().

from itertools import batched

ids = list(range(1, 8))
for chunk in batched(ids, 3):
    print(chunk)

# (1, 2, 3)
# (4, 5, 6)
# (7,)

Good for sending API requests in groups, since many APIs cap how many items you can send at once. The last batch can be shorter, so your code should expect that.

7. any() and all() with a generator

nums = [4, 8, 15, 16, 23, 42]
print(any(n > 40 for n in nums))   # True
print(all(n > 0 for n in nums))    # True

This replaces the “set a flag to False, loop, flip it, break” pattern. Both functions stop early once the answer is known.

Python tricks for beginners and the Python version each one needs

Unpacking and assignment

8. Star unpacking (and the one-line swap)

first, *middle, last = [10, 20, 30, 40, 50]
print(first, middle, last)
# 10 [20, 30, 40] 50

a, b = 1, 2
a, b = b, a
print(a, b)
# 2 1

The starred name always gets a list, even if it’s empty. The swap works because the right side is built as a tuple before anything is assigned.

9. The walrus operator :=

It assigns and returns a value in the same expression. The most readable use is “search, then use the match”:

import re

line = "order #4821 shipped"
if (m := re.search(r"#(\d+)", line)):
    print(m.group(1))

# 4821

Don’t go wild with it. One walrus per if is fine. Three in a comprehension is a puzzle for whoever reads it next.

10. Merge dictionaries with |

defaults = {"theme": "light", "font": 14}
user_prefs = {"theme": "dark"}
settings = defaults | user_prefs
print(settings)

# {'theme': 'dark', 'font': 14}

Added in 3.9. The right-hand dict wins on duplicate keys, which is exactly what you want for “defaults, then overrides”. There’s also |= to update in place.

Watch the difference: | builds a new dictionary and leaves both originals untouched, while |= changes the one on the left. On Python 3.8 or older the operator doesn’t exist at all. The older spelling, {**defaults, **user_prefs}, gives the same result there, and we confirmed it prints the identical dictionary.

The standard library does the boring parts

11. Counter for “how many of each?”

from collections import Counter

words = "the cat and the hat and the bat".split()
print(Counter(words).most_common(2))

# [('the', 3), ('and', 2)]

Word counts, vote tallies, the most common error code in a log file. If the question is “how many of each”, this is the answer.

12. defaultdict(list) for grouping

from collections import defaultdict

files = ["a.py", "b.js", "c.py", "d.md"]
by_ext = defaultdict(list)
for f in files:
    by_ext[f.rsplit(".", 1)[1]].append(f)
print(dict(by_ext))

# {'py': ['a.py', 'c.py'], 'js': ['b.js'], 'md': ['d.md']}

Missing keys get an empty list automatically. No if ext not in by_ext check needed.

13. Sort by two things at once

people = [
    {"name": "Zoe", "age": 25},
    {"name": "Adam", "age": 31},
    {"name": "Mia", "age": 25},
]
for p in sorted(people, key=lambda p: (p["age"], p["name"])):
    print(p["name"], p["age"])

# Mia 25
# Zoe 25
# Adam 31

Return a tuple from the key function and Python sorts by the first item, then breaks ties with the second. Want age descending? Use -p["age"] in the tuple.

A mistake we see a lot: result = people.sort(key=...). The .sort() method sorts the list in place and returns None, so result ends up empty-handed. We ran it, and it printed None. If you want a new sorted list, call sorted(); if you want to change the original, call .sort() and don’t assign it.

14. dataclass instead of a hand-written class

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int = 0

p = Point(3)
print(p)                  # Point(x=3, y=0)
print(p == Point(3, 0))   # True

You get __init__, a readable __repr__ and __eq__ for free. Type hints here are labels only; Python won’t stop you from passing a string as x.

15. pathlib for files and paths

from pathlib import Path

Path("notes.txt").write_text("hello\nworld\n")
print(Path("notes.txt").read_text().splitlines())
# ['hello', 'world']

report = Path("data/report.csv")
print(report.suffix, report.stem)
# .csv report

One object handles reading, writing, extensions and joining folders with /. It also behaves the same on Windows and macOS, which os.path string juggling often doesn’t.

A real cleanup, before and after

Here’s a small job that shows how these pieces add up. You have a messy downloads folder and want to know which file types are taking over. A typical first attempt looks like this:

import os

counts = {}
for name in os.listdir("downloads"):
    if "." in name:
        ext = name.split(".")[-1].lower()
        if ext in counts:
            counts[ext] = counts[ext] + 1
        else:
            counts[ext] = 1
for ext in sorted(counts, key=counts.get, reverse=True):
    print(ext, counts[ext])

It works. Now the same thing with pathlib (trick 15), a generator and Counter (trick 11):

from collections import Counter
from pathlib import Path

counts = Counter(p.suffix.lower() for p in Path("downloads").iterdir() if p.suffix)
for ext, n in counts.most_common():
    print(f"{ext:<6} {n}")

# .jpg   2
# .pdf   2
# .txt   1

We tested both on a folder with six files, including photo.JPG and a README with no extension. Both gave the same counts. The second version is about a third as long, and it has fewer places to hide a bug. The :<6 inside the f-string pads the extension so the numbers line up (trick 2 again).

Which Python version do you need?

Everything on this page runs on Python 3.12 and newer. On 3.10 or 3.11 you lose tricks 3 and 6, and the rest still work. On 3.9 you also lose strict=True, and on 3.8 the dictionary | operator goes as well.

Honestly, though, if you’re on anything older than 3.11, upgrading is the better fix. The official Python version status page lists 3.8, 3.9 and 3.10 as end-of-life, which means no more security fixes. If you’re starting fresh, install the current release from python.org and you won’t have to think about any of this.

One habit that saves a lot of pain once Python is installed: give every project its own environment, so packages from one project can’t break another. Our Python virtual environment guide compares venv, uv and conda with real timings.

The catch: about a third of this list depends on your Python version, and most “Python tricks” articles never say so. batched() and the nested f-string quotes only exist in 3.12+. strict=True needs 3.10. Plenty of servers, older Macs and school lab machines still run something older. Check with python --version before you copy a trick into code that has to run somewhere else.

Which Python tricks for beginners to learn first

If you only take three from this page, take enumerate(), f-strings with =, and defaultdict. You’ll use them every week, they work on any Python from 3.8 up, and they remove the most boilerplate.

The walrus operator is the one we’d hold off on. It’s useful, but beginners tend to cram it everywhere, and code review gets harder for no gain. Learn it, use it in if and while conditions, and stop there.

And if you’re learning with an AI assistant, ask it to rewrite your loops “using the standard library where it helps”. It will often suggest exactly these patterns. Our list of AI prompts for coding has a few refactor prompts that work well for this.

Next: doing the same cleanup in the browser? Read 20 JavaScript one-liners we actually ran in Node. And if your data sits in a database rather than a list, the Counter trick has a cousin in these SQL tricks for cleaner queries, where one GROUP BY does the counting for you. Liked trick #1? We took list comprehensions further in 12 list comprehension patterns, every one of them run on Python 3.12.

FAQ

Do these tricks work in Python 3.11?

Most do. The two exceptions are itertools.batched() and reusing the same quote type inside an f-string, which both need 3.12 or newer.

Are one-liners always better?

No. Shorter is only better when it’s also clearer. A three-line loop that a teammate understands at a glance beats a clever comprehension they have to decode.

Does dataclass check my types?

No. Type hints are not enforced at runtime. Use a type checker such as mypy, or a validation library, if you need that.

How do I check my Python version?

Run python --version in a terminal (on some systems it’s python3 --version). Inside a script, import sys; print(sys.version) does the same.

Leave a Comment