Learning a language by reading its reference is slow, because the reference gives equal weight to what you need every day and what you will never touch. This is the short list, grouped by the job you are doing when you need it.
Looking at what you have
When something behaves unexpectedly, these four tell you what you are actually holding rather than what you assumed.
- type(x) — the class of a value. A string that looks like a number is the most common surprise in any script that reads a file.
- len(x) — the length of a sequence. Works on strings, lists, dictionaries and sets.
- dir(x) — everything you can call on an object. Useful when you half-remember a method name.
- print(f"...") — an f-string is the only string formatting worth learning now.
Turning one collection into another
Most scripts are a pipeline: read something, reshape it, write it back out. These are the reshaping tools, and a comprehension usually reads better than the functional equivalent.
rows = ["12", "7", "31"]
numbers = [int(r) for r in rows] # map, but readable
big = [n for n in numbers if n > 10] # filter, but readable
total = sum(numbers)
largest = max(numbers)
in_order = sorted(numbers, reverse=True)
sorted() returns a new list. list.sort() changes the list in place and returns nothing, which is why x = y.sort() silently gives you None.
Working through data in a loop
Three functions remove almost every awkward loop counter you would otherwise write by hand.
| Function | Use it when |
|---|---|
| enumerate(items) | You need the index as well as the item. Cleaner than keeping a counter variable. |
| zip(a, b) | You are stepping through two lists in parallel, such as names and scores. |
| range(n) | You need a fixed number of repetitions rather than a collection to walk. |
for i, name in enumerate(names, start=1):
print(i, name)
for name, score in zip(names, scores):
print(name, score)
The standard library bits worth memorising
Four imports cover the majority of small automation work, and none of them needs installing.
- pathlib.Path — build and check file paths without string-joining slashes.
- json.load and json.dumps — read and write the format almost every API speaks.
- datetime.strptime — turn a date string into a real date so it can be compared and sorted.
- collections.Counter — count occurrences in one line instead of five.
from collections import Counter
Counter(["a", "b", "a", "c", "a"]).most_common(2)
# [('a', 3), ('b', 1)]
Key takeaways
- F-strings and comprehensions replace most of the string and loop code beginners write.
- enumerate and zip remove hand-rolled counters and index lookups.
- sorted returns a list, sort returns nothing.
- Reach for pathlib, json, datetime and Counter before installing anything.
Turn this into a career, not a bookmark.
Data Science & Analytics with AI takes you from your first pandas import to a portfolio employers read.
Explore the course