iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Everyday Python scripts often get simpler when you use a built-in function or standard-library module instead of writing the same loop or helper again. Here are 10 practical techniques: eight need no separate third-party package, while two rely on modules that may not ship with every Python distribution.
“Zero installs” here means no additional third-party package for that example—not a guarantee that every Python runtime includes every optional standard-library component. The examples use Python 3; check the documentation for your installed version if you need to support older releases.
1. Get an index and a value with enumerate
A manual counter is easy to forget to update. Use enumerate when a loop needs both an item and its position:
names = ["Ada", "Grace", "Linus"]
for number, name in enumerate(names, start=1):
print(f"{number}. {name}")
enumerate yields count-item pairs, and start=1 makes the displayed numbers human-friendly. The count is a position in the iteration, not necessarily an index into the original collection if the iterable itself filters or transforms items.
#1 Best Overall
Python’s functional programming HOWTO documents enumerate and demonstrates using it to number lines.
2. Pair corresponding items with zip
When two iterables contain related values in the same order, zip lets you process them together without indexing both:
names = ["Ada", "Grace", "Linus"]
scores = [94, 98, 91]
for name, score in zip(names, scores):
print(name, score)
Ordinary zip stops as soon as the shortest iterable runs out. It does not report that one input had extra items, so check lengths separately when unequal inputs indicate a data problem.
The Python functional programming HOWTO covers zip as a way to combine corresponding items.
3. Group values with collections.defaultdict
To gather multiple values under each key, a normal dictionary often needs a missing-key check. defaultdict(list) creates a list the first time a key is accessed:
from collections import defaultdict
by_department = defaultdict(list)
for name, department in [("Ada", "Research"), ("Grace", "Engineering"), ("Linus", "Research")]:
by_department[department].append(name)
For counting, defaultdict(int) supplies zero for a new key:
Rank #2
counts = defaultdict(int)
for department in ["Research", "Engineering", "Research"]:
counts[department] += 1
Accessing a missing key creates and stores its default value. If you only want to test whether a key exists, use membership testing rather than indexing it.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesThe collections documentation describes defaultdict and its default factory.
4. Take part of an iterator with itertools.islice
When you need only the first few results from a stream or generator, itertools.islice can bound iteration without building a full list:
from itertools import islice
first_five = list(islice(read_records(), 5))
islice consumes the source iterator as it advances; it does not make the underlying stream reusable. Converting its result to a list stores the selected items, so omit list(...) if downstream code can process the iterator directly.
The itertools documentation describes tools for creating and combining iterators.
5. Build filesystem paths with pathlib.Path
String concatenation can make paths harder to read and less portable. Path represents a filesystem path and lets you join components with the division operator:
from pathlib import Path
report_path = Path("reports") / "summary.txt"
if report_path.exists():
print(report_path.read_text(encoding="utf-8"))
Choose an explicit text encoding when reading or writing files whose encoding matters. A path object does not guarantee that the target exists or that the process has permission to access it.
The pathlib documentation covers object-oriented filesystem paths and their operations.
6. Measure a small snippet with timeit
When comparing two implementations, measure the specific operation rather than assuming one is faster:
Free tools Windows power users keep installed
One-click scans. No signup required.
import timeit
elapsed = timeit.timeit("sum(range(100))", number=10_000)
print(elapsed)
This reports elapsed time for those repetitions on the machine and Python environment where it runs. It is a local observation, not a universal speed ranking; noisy system load and the size or shape of real inputs can change the result.
The timeit documentation explains how to time small code fragments.
7. Cache repeat calls to a pure function with functools.lru_cache
If a function returns the same result for the same arguments and is called repeatedly with those arguments, caching can avoid recomputation:
from functools import lru_cache
@lru_cache(maxsize=128)
def ways_to_climb(steps):
if steps <= 1:
return 1
return ways_to_climb(steps - 1) + ways_to_climb(steps - 2)
Cached arguments must be hashable. The cache lives with the decorated function until entries are evicted or you clear it, so this pattern is unsuitable when results depend on changing external state or when retaining arguments and results would be a problem.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11The functools documentation describes function tools including lru_cache.
8. Sort values with sorted instead of writing a sorting loop
For a straightforward sorted copy, use the built-in function:
scores = [72, 95, 81]
ordered_scores = sorted(scores)
print(ordered_scores)
sorted returns a new list and leaves the original iterable unchanged. That means it materializes the sorted result in memory; for a list you intend to modify in place, use its .sort() method instead.
The functional programming HOWTO explains that sorted returns a sorted list.
Recommended Free Tools
9. Calculate basic descriptive statistics with statistics
For ordinary numerical summaries, the standard-library statistics module avoids hand-coding common formulas:
Best Value
import statistics
readings = [18.2, 19.1, 18.7, 20.0]
print(statistics.mean(readings))
print(statistics.median(readings))
Choose the measure that fits the data: the mean can be pulled by extreme values, while the median reports the middle of the ordered observations. For specialized datasets or statistical analysis, consult the module documentation for the functions’ assumptions and behavior.
The statistics documentation lists the module’s descriptive-statistics functions.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.10. Close files reliably with with
Opening a file and then relying on a later close call leaves cleanup vulnerable to errors or early returns. A with block closes the file when control leaves the block:
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →with open("notes.txt", "r", encoding="utf-8") as file:
text = file.read()
Use a suitable encoding when working with text; the example explicitly requests UTF-8. The path must be accessible, and reading mode expects the file to exist.
Python’s open documentation describes file opening and its parameters.
What “zero installs” means for these examples
The first eight techniques use Python built-ins or standard-library modules and need no separate third-party package when those components are present. The last two examples use statistics and pathlib—correction: these are also standard-library modules, so all ten examples are standard-library or built-in features. That is not a promise that every managed, stripped-down, or operating-system-packaged Python installation includes every component in the same way. Python’s standard library is broad, and its documentation notes that some distributions may require packaging tools to obtain optional components.
Check the standard-library documentation for the Python version and distribution you actually use: Python Standard Library.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
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.

