The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →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.
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.
#1 Best Overall
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.
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.
Rank #2
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.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallfrom 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.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →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.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minute9. Calculate basic statistics with statistics
For straightforward descriptive calculations, the standard library’s statistics module avoids writing common formulas yourself.
Best Value
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.
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:
pathliband awithblock. - Repeated work or measurement:
lru_cachefor suitable pure functions;timeitfor 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.
Quick Recap
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.




