🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Python Cheatsheet: Syntax, Types, and Stdlib

Python ReferenceCheatsheetđŸŸĸ Free Lesson

Python Cheatsheet: Syntax, Types, and Stdlib

A cheatsheet is only useful if it answers the question you actually have while typing. This one is organized the way questions arise: what type is this value, which collection should hold it, how do I transform it, which standard library module already does this, and what is the one-liner that replaces ten lines of loops. Each section pairs a short explanation with the operations you reach for daily, so you can scan the table and still understand why the code looks the way it does.

What You'll Learn

  • 1Identify the built-in types and pick between list, tuple, dict, and set by the access pattern
  • 2Apply comprehensions, unpacking, and the walrus operator without trading clarity for brevity
  • 3Reach for the standard library module that already solves the task
  • 4Use pathlib, context managers, and exceptions as the default style for file work

Values, names, and the types you will use most

Python variables are names bound to objects, and the type lives on the object rather than on the name. Rebinding a name is cheap and does not mutate anything; mutating an object is visible through every name that refers to it. Everything you hold in memory is either a primitive such as an integer or a string, a collection such as a list or dictionary, or an instance of a class, including modules and functions.

Mutability is the property worth memorizing. Lists, dictionaries, and sets can change in place. Numbers, strings, tuples, and frozensets cannot, which is what makes them safe as dictionary keys and as fields in a dataclass that must stay hashable. Choosing a tuple over a list when the data will not change communicates that intent to the next reader and prevents accidental mutation bugs.

python
x = 42              # int
ratio = 3.14        # float
label = "invoice"   # str
flag = True         # bool
nothing = None      # NoneType
row = (1, 2)        # tuple, immutable, hashable
mapping = {"k": "v"}  # dict, insertion ordered
unique = {1, 2, 3}    # set, unordered, unique

int("42"), float("3.14"), str(99), bool([])   # conversions
list("abc"), tuple([1, 2]), set([1, 1, 2])    # collection conversions
dict([("a", 1), ("b", 2)])                    # pairs to dict

Strings: text is a sequence, not a mystery

Strings are immutable sequences of Unicode code points, which is why every method returns a new string rather than editing the old one. Nearly every text task is one of four operations: trim the edges, split into pieces, join pieces back together, or test a property such as emptiness or digit-only. Learn those four and the rest of the method surface becomes discoverable with dir on any string.

Formatting is a separate skill. F-strings win for interpolation because the expression lives where it is used and the format spec is visible at a glance. str.format still matters when the template is built dynamically, and the printf-style operator appears mostly in older code and logging configurations.

python
raw = "  Invoice-2026-0042  "
clean = raw.strip().lower()
parts = clean.split("-")          # ['invoice', '2026', '0042']
prefix = "-".join(parts[:2])      # 'invoice-2026'
clean.startswith("invoice"), clean.endswith("42")
clean.replace("-", "_"), clean.count("2")

total = 1250.5
f"{total:,.2f}"      # '1,250.50'
f"{clean:>24}"       # right aligned in 24 columns
f"{0.8567:.1%}"      # '85.7%'
name, qty = "widget", 3
f"{name} x{qty} = {qty * 2:.2f}"

Alignment and width specifications are the quickest way to produce aligned terminal output without a formatting library. The colon introduces the format spec: fill and alignment, width, thousands separator, precision, and type, in that order.

The four collections and the access pattern that picks them

Choosing a collection is really choosing an access pattern. If you reach for elements by position and the order matters, use a list. If the shape is fixed and the values belong together, use a tuple. If you look values up by a key, use a dictionary. If you only care about membership and uniqueness, use a set. Everything else is a variation on these four.

NeedCollectionCore operationsWatch out for
Ordered, mutable sequencelistappend, pop, sort, sliceMembership tests are linear
Fixed record, hashabletupleindex, unpackOne element needs a trailing comma
Key to value lookupdictget, items, updateKey must be hashable
Unique membershipsetadd, discard, union, intersectUnordered; no indexing

Dictionaries are ordered by insertion in every supported Python version, which means you can iterate and serialize with a predictable order. get with a default avoids the common KeyError, and setdefault or collections.defaultdict removes the check-then-append pattern when grouping.

python
counts = {}
for word in "to be or not to be".split():
    counts[word] = counts.get(word, 0) + 1

from collections import Counter, defaultdict
Counter("to be or not to be").most_common(2)   # [('to', 2), ('be', 2)]

by_len = defaultdict(list)
for word in ["a", "is", "the", "end"]:
    by_len[len(word)].append(word)

{w: len(w) for w in ["a", "is", "the"]}        # dict comprehension
{c for c in "abcabc" if c != "b"}              # {'a', 'c'}

Comprehensions are the idiomatic way to build collections, and they should stay flat. A comprehension with multiple for clauses and nested conditionals is usually clearer as an explicit loop. The walrus operator earns its place when a value is computed once and then used twice, such as a length test followed by processing.

Control flow, functions, and the small superpowers

Loops in Python iterate over iterables directly, which is why you rarely need an index variable. enumerate supplies positions when you need both, zip walks several sequences together, and reversed or sorted produce a new sequence without touching the original. break exits the innermost loop, continue skips to the next iteration, and else on a loop runs when the loop finished without breaking, a feature that reads oddly until you see it used for search patterns.

Functions are first-class objects: they can be stored, passed, and returned. Default arguments must be immutable, because a mutable default is created once at definition time and shared across every call, which is one of the most reproduced bugs in the language. Keyword-only arguments after a bare star make call sites self-documenting.

python
for index, item in enumerate(["a", "b"], start=1):
    print(index, item)

for left, right in zip([1, 2], ["x", "y"]):
    print(left, right)

status = "adult" if age >= 18 else "minor"

def greet(name, greeting="Hello", *, punctuation="!"):
    return f"{greeting}, {name}{punctuation}"

first, *middle, last = [1, 2, 3, 4, 5]
n = len(data) if (n := len(data)) > 10 else 0   # walrus
merged = dict1 | dict2                          # 3.9+

Errors and files: the defaults you should not fight

Exceptions communicate failure with structure. Catch the most specific type you can handle, let unexpected ones propagate, and use else and finally to separate the success path from cleanup. Custom exceptions should subclass the standard hierarchy so that existing except clauses keep working.

File work is safest with context managers, because the block boundary is the resource boundary. pathlib has largely replaced os.path for path manipulation: the slash operator joins segments, and the object offers exists, glob, read_text, and write_text without open-mode strings to remember.

python
try:
    value = int(raw)
except ValueError as exc:
    print(f"bad input: {exc}")
else:
    process(value)
finally:
    cleanup()

from pathlib import Path

path = Path("data") / "reports" / "q1.txt"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("ok", encoding="utf-8")
text = path.read_text(encoding="utf-8")
sorted(Path(".").glob("*.py"))

Iteration tools that replace nested loops

Before writing a nested loop, check whether a standard tool expresses the same traversal more clearly. itertools.chain flattens consecutive sequences without building an intermediate list. groupby collapses a sorted sequence into runs, which is the idiomatic way to summarize grouped data without a dictionary of lists. product and permutations and combinations express the enumeration cases that otherwise become two or three nested loops with index bookkeeping. zip walks several sequences in lockstep, and zip(..., strict=True) turns a silent length mismatch into an error, which is what you want when the sequences are supposed to match.

python
from itertools import chain, groupby, combinations

rows = [("a", 1), ("a", 2), ("b", 3)]
for key, group in groupby(rows, key=lambda r: r[0]):
    print(key, [v for _, v in group])

list(chain([1, 2], [3]))
list(combinations("abc", 2))   # [('a','b'), ('a','c'), ('b','c')]

The habit worth building is to read a proposed nested loop as a statement about shapes: is this a cross product, a flattening, a grouping, or a lockstep walk? Once named, the matching tool is usually shorter, faster because it lives in C, and clearer to the next reader who has to modify it.

The standard library shortlist

Before adding a dependency, check the standard library. json handles serialization, datetime plus timedelta handles all calendar arithmetic you are likely to need, re handles pattern matching, and math covers the numeric functions people reimplement. itertools provides the iteration primitives that otherwise become nested loops, and functools provides caching, partial application, and reduction.

python
import json, math, random
from datetime import datetime, timedelta
from itertools import chain, groupby, islice, product
from functools import lru_cache, partial, reduce

json.dumps({"a": 1}); json.loads('{"a": 1}')
now = datetime.now(); yesterday = now - timedelta(days=1)
random.choice(["heads", "tails"]); random.sample(range(10), 3)
math.ceil(3.2); math.sqrt(16); math.gcd(12, 8)
list(islice(chain([1, 2], [3, 4]), 3))
reduce(lambda a, b: a + b, [1, 2, 3], 0)

os, sys, and subprocess cover process and environment boundaries; logging replaces print for anything that outlives a single debugging session; unittest and pytest cover tests. Knowing these names exists is usually enough to stop writing a hundred lines that a two-line import would have replaced.

Common Mistakes

Using a list for membership tests inside a loop

Fix: Convert to a set once so each test is a constant-time hash lookup instead of a linear scan

Mutating a default argument and wondering why state leaks between calls

Fix: Use None as the default and create the list or dictionary inside the function body

Building strings with plus inside a loop

Fix: Collect the pieces and call join once, because each concatenation allocates a new string object

Catching a broad exception to keep a script running

Fix: Catch the specific exception you can handle and let everything else surface with its traceback

Best Practices

  • Pick the collection by access pattern, not by habit
  • Prefer comprehensions for flat transformations and explicit loops for anything nested
  • Use pathlib and context managers as the default file-handling style
  • Search the standard library before writing utility code or adding a package
  • Keep type hints on public signatures so the next reader knows the contract

Interview Questions

Q1: Why can a list not be a dictionary key?

Dictionary keys must be hashable, meaning they have a stable hash and do not change. Lists are mutable, so their hash is undefined, and Python raises TypeError rather than silently corrupting the table.

Q2: What does the walrus operator buy you?

It binds a name in the middle of an expression so a value can be computed once and reused, which avoids repeating an expensive call or a long expression in a condition and its body.

Q3: When would you choose setdefault over a dictionary comprehension?

When grouping incrementally as you iterate and you want one pass. For a single static mapping built from an existing iterable, a comprehension is clearer and faster.

Key Takeaways

  • Variables are names bound to typed objects; mutability is the property that drives design choices
  • The four built-in collections map cleanly onto four access patterns
  • F-strings with format specs handle nearly all formatting without a library
  • pathlib plus context managers is the default style for file and path work
  • The standard library covers serialization, dates, iteration, and caching before you reach for a package
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement