DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk4 min

10 Practical Python Tricks for Everyday Scripts—8 Need No Extra Packages

Ten practical Python techniques for ordinary scripts, including eight that need no third-party package, with examples and the caveats that matter.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Most everyday Python tasks don’t need a new package. The examples below cover ten useful techniques, eight of which rely only on Python’s built-ins or standard library. “No extra package” means you don’t install a third-party dependency for that example; a particular Python distribution may omit optional standard-library components.

The code targets Python 3. Check the documentation for your installed version if you need to confirm availability or distribution-specific details.

As an Amazon Associate I earn from qualifying purchases.

1. Get an index and a value with enumerate

When a loop needs both each item and its position, avoid maintaining a separate counter.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Before:

items = ["apples", "pears", "plums"]
i = 1
for item in items:
    print(i, item)
    i += 1

After:

for i, item in enumerate(items, start=1):
    print(i, item)

enumerate yields count-and-item pairs. Use start=1 for human-facing numbering; omit it when you want the usual zero-based count. Python’s Functional Programming HOWTO also demonstrates using it to number lines.

2. Pair parallel data with zip

If two iterables hold corresponding values, zip lets one loop process them together.

Before:

for i in range(len(names)):
    print(names[i], scores[i])

After:

for name, score in zip(names, scores):
    print(name, score)

Ordinary zip stops as soon as the shortest input runs out. It does not report that the input lengths differ, so check lengths separately when silently skipping unmatched values would be a bug.

3. Group values with collections.defaultdict

When collecting multiple values under each key, a defaultdict(list) creates a new empty list the first time a key is used.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Before:

groups = {}
for category, value in records:
    if category not in groups:
        groups[category] = []
    groups[category].append(value)

After:

from collections import defaultdict

groups = defaultdict(list)
for category, value in records:
    groups[category].append(value)

For counting, use defaultdict(int) and increment a key. A missing key then starts at zero. The collections documentation describes the available container types and their behavior.

4. Take a bounded slice of an iterator with itertools.islice

When an iterable may be large or is produced on demand, itertools.islice can take a bounded portion without first turning the whole iterable into a list.

from itertools import islice

first_five = list(islice(records, 5))

islice consumes the source iterator as it produces those items. The surrounding list stores the selected items, so leave it out if you want to process them one at a time. The Functional Programming HOWTO explains iterator-based workflows.

5. Work with filesystem paths using pathlib.Path

Instead of manually joining path strings, use Path to express filesystem operations with path objects.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from pathlib import Path

report = Path("data") / "report.txt"
if report.exists():
    print(report.read_text(encoding="utf-8"))

The slash operator combines path components, and read_text reads a text file. Specifying an encoding avoids relying on the machine’s default text encoding. Filesystem operations can still fail—for example, because a file is missing or access is denied. See the pathlib documentation.

6. Measure a small fragment with timeit

When you want to compare small pieces of code, timeit can run them repeatedly and report a measurement on your machine.

import timeit

elapsed = timeit.timeit(
    "sum(range(100))",
    number=10_000,
)
print(elapsed)

This is a local measurement for that code and environment, not a universal ranking of Python techniques. For meaningful comparisons, keep the setup and conditions consistent. The timeit documentation describes its options and command-line interface.

7. Cache repeated calls with functools.lru_cache

If a pure function is called repeatedly with the same arguments, an LRU cache can reuse earlier results.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from functools import lru_cache

@lru_cache(maxsize=128)
def ways(n):
    if n < 2:
        return 1
    return ways(n - 1) + ways(n - 2)

Cached arguments must be hashable, and the cache remains associated with the function until cleared or discarded. Caching is a poor fit when results depend on changing external state or when keeping old results in memory is undesirable. See functools.

8. Sort in one expression with sorted

For a new sorted result, use sorted rather than writing a sorting loop.

Before: manually building a sorted result requires implementing or adapting a sorting process.

After:

names = ["Mina", "Ari", "Zoe"]
ordered_names = sorted(names)

sorted returns a new list, so it materializes the result. The original iterable is not changed. For custom ordering, pass a key function, such as sorted(names, key=str.lower). The Functional Programming HOWTO describes its list result.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

9. Calculate basic statistics with statistics

For straightforward descriptive calculations, the standard library’s statistics module avoids writing common formulas yourself.

from statistics import mean, median

scores = [72, 84, 91, 91]
print(mean(scores))
print(median(scores))

Choose the statistic that fits the question: the mean is the arithmetic average, while the median is the middle value (or the midpoint of the two middle values). For missing data, weighted observations, or more specialized statistical work, check the module’s documented assumptions and functions. See the statistics documentation.

10. Close files reliably with with

A context manager closes a file when its block ends, including when an exception occurs.

Before: opening a file and remembering to close it on every path makes cleanup easy to miss.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

After:

with open("notes.txt", encoding="utf-8") as file:
    text = file.read()

Use the encoding appropriate for the file; UTF-8 is common, but it is not guaranteed for every existing text file. The open documentation explains file modes and encoding.

Which techniques to reach for first

  • Index and value: enumerate.
  • Corresponding items from inputs: zip, after deciding how mismatched lengths should be handled.
  • Accumulating by key: defaultdict.
  • Lazy or bounded iteration: itertools.
  • Paths and files: pathlib and a with block.
  • Repeated work or measurement: lru_cache for suitable pure functions; timeit for a small local comparison.

Python’s standard library is extensive, but “zero installs” is not a guarantee that every runtime includes every optional component. Python distributions and operating-system packages can differ, so check your environment if an import is unavailable.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.