Python 3 cheat sheet
A scannable Python 3 reference: 21 short snippets across 8 topics, each linking back to the lesson it came from.
At a glance
| Topic | What it covers | |
|---|---|---|
| Python: getting started | Python uses indentation instead of braces to delimit blocks. Four spaces per level is the convention — and mixing tabs | lesson |
| Strings | Python 3 keeps a clear boundary: str is Unicode text, bytes is raw data. Convert explicitly at the edges of your | lesson |
| Lists, dicts and comprehensions | Assignment copies the reference, so two names can point at one list. The classic bug is a default mutable argument | lesson |
| Functions and modules | A function with no return gives None. Return early for guard clauses rather than nesting — flatter code reads better | lesson |
| Errors, files and virtualenvs | Tracebacks print oldest call first — scroll to the bottom for the actual exception. The last few frames are almost | lesson |
| Type hints and static checking | Annotations are ordinary objects attached to the function; Python does not enforce them at runtime. Their value is that | lesson |
| Testing with pytest | pytest discovers files named test_*.py or *_test.py, and functions named test_* inside them. There is no class to | lesson |
| Packaging, project layout and pyproject.toml | Put importable code under src/. That one directory of indirection prevents Python from importing your working directory | lesson |
Quick snippets
Python: getting started
Running code
python --version
python hello.py
# interactive REPL - the fastest way to experiment
python
>>> 2 + 3
5
Indentation is syntax
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
else:
grade = 'C'
print(grade) # B
Core types
x, y = 1, 2 # multiple assignment
x, y = y, x # swap without a temp
n = 10
print(f'n is {n}') # f-strings: the modern way to format
print(type(n).__name__)Full lesson: Python: getting started →
Strings
Creating and slicing
s = 'Python'
print(s[0]) # P
s[-1] # n negative index counts from the end
s[0:2] # 'Py' end index is exclusive
s[::-1] # 'nohtyP' reversed
len(s) # 6
print('py' in s.lower()) # True - membership test
Methods worth memorizing
csv = ' a, b , c '
fields = [f.strip() for f in csv.strip().split(',')]
print(fields) # ['a', 'b', 'c']
path = '/var/log/app.log'
path.rsplit('/', 1)[-1] # 'app.log' - split from the right
Building strings efficiently
# slow: each += allocates a brand new string
out = ''
for line in lines:
out += line + '\n'
# fast: one pass, one allocation
out = '\n'.join(lines)
Lists, dicts and comprehensions
Lists
nums = [3, 1, 2]
nums.append(4) # [3, 1, 2, 4]
nums.extend([5, 6])
nums.insert(0, 0)
last = nums.pop() # removes and returns the last item
nums.sort() # in place; sorted(nums) returns a copy
first, *rest = nums # unpacking
Comprehensions
squares = [n * n for n in range(10)]
evens = [n for n in nums if n % 2 == 0]
# dict comprehension
by_id = {u['id']: u for u in users}
# conditional transformation
labels = ['even' if n % 2 == 0 else 'odd' for n in nums]
# set comprehension - deduplicates
unique_tags = {t.lower() for t in tags}
Dicts
user = {'id': 1, 'name': 'Ada'}
user.get('email') # None instead of KeyError
user.get('email', 'n/a') # with default
user.setdefault('role', 'guest')
for key, value in user.items():
print(key, value)
merged = {**user, 'role': 'admin'} # Python 3.5+
counts = dict(Counter(words)) # tallying done for youFull lesson: Lists, dicts and comprehensions →
Functions and modules
Arguments
def greet(name, greeting='Hello', *extra, punct='!', **opts):
"""Docstring: what this function is for."""
parts = [greeting, name, *extra]
sep = opts.get('sep', ' ')
return sep.join(parts) + punct
greet('Ada') # Hello Ada!
greet('Ada', punct='?') # keyword-only must be named
greet('Ada', 'Hi', punct='.')
Returning values
def divide(a, b):
return a / b
q, r = divmod(10, 3) # multiple return values are a tuple
name, _, score = row # _ conventionally means 'ignored'
def find(users, uid):
return None # explicit absence beats raising for 'not found'
Modules and imports
# maths.py
def area(r): return 3.14159 * r * r
if __name__ == '__main__':
print(area(2)) # only when run directly
# consumer
from maths import area
import maths as m
from pathlib import PathFull lesson: Functions and modules →
Errors, files and virtualenvs
Reading a traceback
Traceback (most recent call last):
File 'app.py', line 12, in <module>
main()
File 'app.py', line 8, in main
print(items[5])
~~~~~^^^
IndexError: list index out of range
Files with context managers
with open('data.json', encoding='utf-8') as f:
data = json.load(f) # file closed even on error
with open('out.txt', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
for line in pathlib.Path('app.log').read_text(encoding='utf-8').splitlines():
if 'ERROR' in line:
print(line)
Environments and packages
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install requests
pip freeze > requirements.txt
pip install -r requirements.txtFull lesson: Errors, files and virtualenvs →
Type hints and static checking
Running the checker
pip install mypy
mypy src/ # basic run
mypy --strict src/ # maximum checking
mypy --install-types # fetch stubs for third-party packages
python -m mypy --show-error-codes src/
Running the checker
[tool.mypy]
python_version = "3.11"
warn_unused_ignores = true
warn_redundant_casts = true
disallow_untyped_defs = true
ignore_missing_imports = true
[[tool.mypy.overrides]]
module = "legacy.*"
ignore_errors = trueFull lesson: Type hints and static checking →
Testing with pytest
Files, discovery and asserts
pytest # run everything
pytest tests/test_cart.py # one file
pytest -k "quantity and not slow" # filter by name
pytest -x # stop at the first failure
pytest -vv -s # verbose, do not capture output
pytest --lf # rerun only what failed last timeFull lesson: Testing with pytest →
Packaging, project layout and pyproject.toml
pyproject.toml
# src/shop_tools/__init__.py
__version__ = "0.3.1"
# read the version from one place instead of two
# [project] dynamic = ["version"]
# [tool.hatch.version] path = "src/shop_tools/__init__.py"
Building, publishing and pinning
pip install build twine
python -m build # writes dist/*.tar.gz and dist/*.whl
twine check dist/*
twine upload --repository testpypi dist/* # rehearse first
twine upload dist/* # then the real index
pip install dist/shop_tools-0.3.1-py3-none-any.whl # verify locally
Building, publishing and pinning
# applications: pin exactly, reproducibly
pip freeze > requirements.txt
pip install -r requirements.txt
# modern alternatives
pip install -r requirements.txt --require-hashes
uv lock && uv sync
pip-compile requirements.in -o requirements.txtFull lesson: Packaging, project layout and pyproject.toml →
FAQ
Is this Python 3 cheat sheet free to use?
Where do the examples come from?
How do I go deeper than a cheat sheet?
Related cheat sheets
NumPy pandas Matplotlib Jupyter Notebook Flask FastAPI
Last refreshed 2026-09-27.