Variables & Types
x = 42Integer - no declaration keyword neededx = 3.14Floatx = "hello" # or 'hello'String - single and double quotes are equivalentx = True / FalseBoolean - capitalisedx = NoneNone - absence of a value (like null)x = [1, 2, 3]Listx = (1, 2, 3)Tuple - immutable listx = {1, 2, 3}Set - unordered, unique valuesx = {"a": 1, "b": 2}Dicttype(x)Returns the type object, e.g. isinstance(x, int)True if x is an instance of int (or subclass)int("42") / float("3.14") / str(42)Type conversionbool(0) / bool("") / bool([])Falsy values: 0, 0.0, "", [], {}, (), None, Falsex: int = 42Type annotation (hint only - not enforced at runtime)a, b, c = 1, 2, 3Multiple assignment / unpackinga, *rest = [1, 2, 3, 4]Starred unpacking - rest = [2, 3, 4]x = y = 0Chain assignmentStrings
f"Hello, {name}!"f-string interpolation (preferred, Python 3.6+)f"{value:.2f}"f-string with format spec - 2 decimal places"Hello" + " " + "World"Concatenation with +"ab" * 3Repeat: "ababab"len(s)Number of characterss[0] / s[-1]First / last character (negative indexes from end)s[1:4] / s[:3] / s[2:]Slicing: start:stop (stop exclusive)s[::-1]Reverse strings.upper() / s.lower()Change cases.strip() / s.lstrip() / s.rstrip()Strip whitespace from both / left / rights.split(",") / s.split()Split on delimiter / split on any whitespace",".join(["a", "b", "c"])Join list into string: "a,b,c"s.replace("old", "new")Replace all occurrencess.find("sub") / s.index("sub")First index of substring - find returns -1, index raises ValueErrors.startswith("pre") / s.endswith("suf")Check prefix / suffix"sub" in sTrue if substring founds.count("x")Count non-overlapping occurrencess.zfill(5)Left-pad with zeros to width: "0042"s.center(20, "-")Centre string in field of width padded with char"""multiline\nstring"""Triple-quoted string - preserves newlinesr"\n is literal"Raw string - backslashes not treated as escapesLists, Tuples & Sets
lst = [1, 2, 3]List literal - mutable, orderedlst.append(4)Add to endlst.extend([4, 5])Add all items from iterablelst.insert(1, "x")Insert at indexlst.pop() / lst.pop(0)Remove and return last / item at indexlst.remove("x")Remove first occurrence of value (raises ValueError if missing)del lst[1]Delete item at indexlst[1:3] = []Delete a slicelen(lst)Number of items"x" in lstTrue if value existslst.index("x")First index of valuelst.count("x")Number of occurrenceslst.sort() / lst.sort(reverse=True)Sort in placesorted(lst) / sorted(lst, key=len)Return new sorted listlst.reverse()Reverse in placelst + [4, 5]Concatenate - returns new listlst * 3Repeat list N timeslist(range(5))Create list from range: [0,1,2,3,4]tup = (1, 2, 3)Tuple - immutable; single-item tuple needs trailing comma: (1,)a, b = tup[:2]Unpack tuples = {1, 2, 3}Set - unordered, unique elementss.add(4) / s.discard(2)Add element / remove if present (no error)s1 | s2 / s1 & s2 / s1 - s2 / s1 ^ s2Union / intersection / difference / symmetric differences1.issubset(s2) / s1.issuperset(s2)Subset / superset checkDicts
d = {"a": 1, "b": 2}Dict literald["a"]Access by key - raises KeyError if missingd.get("a") / d.get("a", 0)Safe access - returns None or default if missingd["c"] = 3Add or update keydel d["a"]Remove key (raises KeyError if missing)d.pop("a") / d.pop("a", None)Remove and return value / with default"a" in dTrue if key existsd.keys() / d.values() / d.items()View objects of keys / values / (key, value) pairsd.update({"c": 3})Merge another dict (in place){**d1, **d2}Merge dicts - d2 values win on duplicate keysd | {"c": 3}Merge with | operator (Python 3.9+)d.setdefault("a", 0)Return value if key exists, else insert and return defaultdict.fromkeys(["a","b"], 0)Create dict with keys from iterable, all set to defaultlen(d)Number of key-value pairsfor k, v in d.items():Iterate key-value pairsControl Flow
if x > 0:Indentation defines blocks - no bracesif x > 0: ... elif x < 0: ... else: ...if / elif / else"pos" if x > 0 else "neg"Ternary / conditional expressionfor item in iterable:Iterate over any iterablefor i, val in enumerate(lst):Iterate with indexfor a, b in zip(lst1, lst2):Iterate two lists in parallelfor k, v in d.items():Iterate dict key-value pairsfor i in range(10): / range(2, 10) / range(0, 10, 2)Range: stop / start,stop / start,stop,stepwhile condition:Loop while condition is truebreak / continue / passExit loop / skip iteration / no-op placeholderfor ... else: / while ... else:else block runs if loop completed without breakmatch x:Structural pattern matching (Python 3.10+)case 1: / case str(): / case [a, b]: / case _:Literal / type / sequence / wildcard patternFunctions
def greet(name): return f"Hello, {name}"Function definitiondef greet(name: str) -> str:With type hintsdef greet(name="World"):Default parameter valuedef fn(*args):Variadic positional args - collected as tupledef fn(**kwargs):Variadic keyword args - collected as dictdef fn(*args, **kwargs):Accept any combination of positional and keyword argsfn(a, b, *lst)Unpack list as positional argsfn(**{"a": 1})Unpack dict as keyword argslambda x: x * 2Anonymous function - single expressionlambda x, y: x + yLambda with multiple paramsglobal xDeclare intent to modify a global variablenonlocal xDeclare intent to modify a variable in enclosing scopedef outer():\n def inner(): ...\n return innerClosure - inner function captures outer scopefrom functools import lru_cache\n@lru_cacheMemoisation decoratorClasses
class Dog:Class definitionclass Dog(Animal):Inherit from Animaldef __init__(self, name):\n self.name = nameConstructor - self is the instancedef bark(self): ...Instance method - first param is always self@classmethod\ndef create(cls): ...Class method - receives the class, not instance@staticmethod\ndef helper(): ...Static method - no implicit first argument@property\ndef name(self): return self._nameGetter property@name.setter\ndef name(self, val): self._name = valSetter propertysuper().__init__(args)Call parent class constructorisinstance(obj, Dog)True if obj is a Dog (or subclass)issubclass(Dog, Animal)True if Dog inherits from Animaldef __str__(self): return self.name__str__ - called by str() and print()def __repr__(self): return f"Dog({self.name!r})"__repr__ - unambiguous representation for debuggingdef __len__(self): / __eq__(self, other): / __lt__(self, other):Dunder methods for len(), ==, <from dataclasses import dataclass\n@dataclass\nclass Point:\n x: float\n y: floatDataclass - auto-generates __init__, __repr__, __eq__Comprehensions & Generators
[x * 2 for x in lst]List comprehension - transform each item[x for x in lst if x > 0]List comprehension with filter[f(x) for x in lst if pred(x)]Transform + filter combined[x for row in matrix for x in row]Nested loops - flattens 2D list{k: v for k, v in d.items()}Dict comprehension{k: v for k, v in d.items() if v > 0}Dict comprehension with filter{x * 2 for x in lst}Set comprehension - deduplicated results(x * 2 for x in lst)Generator expression - lazy, memory-efficientsum(x * 2 for x in lst)Pass generator directly to a functionlist(map(fn, lst))map() - equivalent to [fn(x) for x in lst]list(filter(pred, lst))filter() - equivalent to [x for x in lst if pred(x)]from functools import reduce\nreduce(lambda a, b: a + b, lst)reduce() - fold list to single valueCommon Built-ins
print(x, y, sep=", ", end="")Print with custom separator and line endinginput("Prompt: ")Read a line from stdin as stringrange(start, stop, step)Lazy integer sequencelen(x) / sum(x) / min(x) / max(x)Length / sum / min / max of iterableabs(x) / round(x, 2) / pow(x, n)Absolute value / round / exponentsorted(x, key=fn, reverse=True)Return sorted listreversed(lst)Return reverse iterator (wrap in list() to materialise)zip(a, b, strict=True)Pair up iterables; strict=True raises if lengths differenumerate(lst, start=1)Pairs of (index, value)any(pred(x) for x in lst)True if any element is truthyall(pred(x) for x in lst)True if all elements are truthyopen("file.txt", "r") as fOpen file for readingf.read() / f.readlines() / f.readline()Read all / lines list / one lineopen("file.txt", "w") as f:\n f.write("text")Open for writing (truncates)import os\nos.path.exists(p) / os.path.join(a, b)File path utilitiesimport json\njson.dumps(obj) / json.loads(s)Encode to JSON string / decode from JSON stringimport re\nre.search(r"pattern", s)Regex search - returns Match or Nonefrom datetime import datetime\ndatetime.now()Current local datetimefrom copy import copy, deepcopyShallow copy / deep copyError Handling
try:\n ...\nexcept ValueError as e:\n ...Catch specific exceptionexcept (TypeError, ValueError) as e:Catch multiple exception typesexcept Exception as e:Catch any exception (broad catch)except:Bare except - catches everything including SystemExit; avoidelse:else block runs only if no exception was raisedfinally:finally block always runs - use for cleanupraise ValueError("bad input")Raise an exceptionraise ValueError("msg") from original_errorChain exceptions - preserves original tracebackraise # bare raiseRe-raise the current exceptionclass AppError(Exception):\n passCustom exception classclass ValidationError(AppError):\n def __init__(self, field, msg):\n super().__init__(f"{field}: {msg}")Custom exception with fieldsstr(e) / repr(e)Exception message / full representationimport traceback\ntraceback.print_exc()Print full traceback to stderrtraceback.format_exc()Get full traceback as stringwith open("file.txt") as f:Context manager - file closed automatically on exit or errorclass Managed:\n def __enter__(self): return self\n def __exit__(self, exc_type, exc, tb): ...Implement context manager protocolfrom contextlib import contextmanager\n@contextmanager\ndef managed():\n yield valueGenerator-based context managerfrom contextlib import suppress\nwith suppress(FileNotFoundError):\n os.remove(path)Silently ignore specific exceptionsModules & Imports
import osImport module - access as os.path.join()import os as operating_systemImport with aliasfrom os import path, getcwdImport specific namesfrom os.path import join, existsImport from sub-modulefrom . import moduleRelative import from same packagefrom ..utils import helperRelative import from parent packageif __name__ == '__main__':
main()Only run as script, not when imported__all__ = ["MyClass", "my_func"]Control what from module import * exportsimport importlib\nimportlib.reload(module)Reload a module at runtimepip install requestsInstall a packagepip install -r requirements.txtInstall from requirements filepip freeze > requirements.txtSave current environment to requirements filepython -m venv .venvCreate virtual environmentsource .venv/bin/activateActivate virtual environment (Linux/macOS).venv\Scripts\activateActivate virtual environment (Windows)python -m module_nameRun module as scriptStandard Library Highlights
from pathlib import Path\nPath("dir/file.txt").read_text()Read file with pathlibPath("dir/file.txt").write_text("content")Write filePath("dir").mkdir(parents=True, exist_ok=True)Create directory treelist(Path(".").glob("**/*.py"))Recursive globimport shutil\nshutil.copy(src, dst) / shutil.move(src, dst)Copy / move filesshutil.rmtree("dir")Remove directory tree recursivelyfrom collections import defaultdict\ndd = defaultdict(list)Dict with automatic default valuefrom collections import Counter\nCounter(["a","b","a"])Count element frequencies: Counter({"a":2,"b":1})from collections import deque\ndq = deque(maxlen=100)Double-ended queue with optional max lengthfrom itertools import chain, product, combinations, permutationsCommon itertoolslist(chain([1,2],[3,4]))Flatten iterables: [1,2,3,4]list(combinations("ABC", 2))All combinations of length 2import sys\nsys.argv / sys.exit(1) / sys.pathCLI args / exit / module search pathsimport subprocess\nresult = subprocess.run(["ls", "-la"], capture_output=True, text=True)Run subprocess and capture outputimport threading\nt = threading.Thread(target=fn, args=(x,))\nt.start(); t.join()Run function in threadimport logging\nlogging.basicConfig(level=logging.INFO)\nlogging.info("msg")Basic logging setup