๐Ÿ Python

โ† Back to Cheatsheets

A quick-reference cheatsheet for the most commonly used Python features. Python is a dynamically typed, interpreted language that emphasises readability. Everything is an object, functions are first-class, and the standard library covers most everyday needs without extra dependencies.

Resources

docs.python.org โ€” Official docs Standard Library reference PEP 8 โ€” Style guide Real Python โ€” Tutorials PyPI โ€” Package index

Built-in Functions

These are always available without importing. They cover the most common operations on iterables, types, and I/O. Prefer them over manual loops where possible โ€” they are implemented in C and clearly communicate intent.

String Methods

Strings are immutable sequences of Unicode characters. All methods return new strings โ€” nothing mutates in place. f-strings (Python 3.6+) are the preferred way to format: faster than % formatting and more readable than .format().

List / Dict / Set

Python's core data structures. Lists are ordered and mutable, dicts map keys to values (insertion-ordered since 3.7), and sets store unique elements with O(1) membership testing. Comprehensions are idiomatic and often faster than equivalent loops. The collections module provides specialised variants for common patterns.

Classes & OOP

Python supports single and multiple inheritance with duck typing โ€” if it has the right methods, it works. @dataclass removes boilerplate for simple data containers and is the modern replacement for writing __init__ by hand. Dunder (double-underscore) methods let you define how objects behave with operators and built-in functions.

Error Handling

Exceptions propagate up the call stack until caught. Always catch specific exception types โ€” bare except: silences every error including KeyboardInterrupt. Context managers (with) guarantee cleanup code runs even if an exception is raised, making them the idiomatic way to manage resources like files and locks.

Common Patterns

Idiomatic Python ("Pythonic") code favours readability and conciseness. Comprehensions, generators, and unpacking are core tools. Type hints (Python 3.5+) improve editor support and catch bugs early without being enforced at runtime โ€” use mypy or pyright to check them.