Python Cheat Sheet
Essential Python syntax, runtime patterns, standard-library helpers, and environment commands worth keeping close while building production code.
Variables & Data Types
10 commandsx = 10Integer
pi = 3.14Float
name = "Alice"String
active = TrueBoolean
items = [1, 2, 3]List (mutable)
coords = (1, 2)Tuple (immutable)
unique = {1, 2, 3}Set (unique values)
user = {"name": "A"}Dictionary
type(x)Check type
isinstance(x, int)Type check (preferred)
String Operations
10 commandsf"Hello {name}"f-string formatting
s.upper() / s.lower()Case conversion
s.strip()Remove whitespace
s.split(",") Split into list
",".join(list)Join list to string
s.replace("a","b")Replace substring
s.startswith("hi")Check prefix
s[1:5]Slice (index 1 to 4)
s[::-1]Reverse string
len(s)String length
List Operations
10 commandslst.append(x)Add to end
lst.insert(0, x)Insert at index
lst.pop()Remove & return last
lst.remove(x)Remove first occurrence
lst.sort()Sort in place
sorted(lst)Return sorted copy
lst[:3]First 3 elements
lst[-1]Last element
[x*2 for x in lst]List comprehension
[x for x in lst if x>0]Filtered comprehension
Dictionary Operations
10 commandsd["key"]Get value (KeyError if missing)
d.get("key", default)Get with default
d["key"] = valueSet value
del d["key"]Delete key
"key" in dCheck key exists
d.keys()All keys
d.values()All values
d.items()Key-value pairs
d.update(d2)Merge dictionaries
{**d1, **d2}Merge (Python 3.5+)
Control Flow
9 commandsif x > 0:If statement
elif x == 0:Else if
else:Else
for x in range(10):For loop
for i, v in enumerate(lst):Loop with index
while condition:While loop
break / continueLoop control
x if cond else yTernary operator
match value:Pattern matching (3.10+)
Functions
8 commandsdef fn(x, y=10):Function with default
def fn(*args):Variable positional args
def fn(**kwargs):Variable keyword args
lambda x: x * 2Anonymous function
@decoratorDecorator syntax
-> int:Return type hint
return a, bReturn tuple
yield xGenerator function
Error Handling
5 commandstry: ... except Exception as e:Catch exception
finally:Always executes
raise ValueError("msg")Raise exception
assert x > 0, "msg"Assert condition
with open("f") as f:Context manager
File I/O
8 commandsopen("f.txt", "r")Read mode
open("f.txt", "w")Write (overwrite)
open("f.txt", "a")Append mode
f.read()Read entire file
f.readlines()Read lines as list
f.write("text")Write string
json.load(f)Parse JSON file
json.dumps(obj)Object to JSON string
OOP (Classes)
9 commandsclass Dog:Define class
def __init__(self):Constructor
self.name = nameInstance variable
@propertyGetter property
@staticmethodNo self/cls access
@classmethodAccess via cls
class B(A):Inheritance
super().__init__()Call parent constructor
@dataclassAuto __init__, __repr__
Useful Built-ins
9 commandsmap(fn, iterable)Apply fn to each
filter(fn, iterable)Keep if fn returns True
zip(a, b)Pair elements
any([True, False])True if any True
all([True, True])True if all True
sum(lst)Sum of numbers
max(lst) / min(lst)Max / min value
abs(-5)Absolute value
round(3.14, 1)Round to 1 decimal
Virtual Environments
7 commandspython -m venv venvCreate venv
source venv/bin/activateActivate (Linux/Mac)
venv\Scripts\activateActivate (Windows)
deactivateDeactivate venv
pip install pkgInstall package
pip freeze > req.txtSave dependencies
pip install -r req.txtInstall from file
Common Imports
7 commandsimport os, sys, jsonStandard library
from pathlib import PathModern file paths
from datetime import datetimeDate/time
from collections import Counter, defaultdictSpecial containers
from typing import List, Dict, OptionalType hints
import reRegular expressions
from functools import lru_cacheMemoization
Async / Await
10 commandsimport asyncioImport async module
async def fetch():Define async function
await coroutine()Wait for async result
asyncio.run(main())Run async entry point
asyncio.gather(a(), b())Run concurrently
asyncio.create_task(coro())Schedule in background
async for item in aiter:Async iteration
async with aopen('f') as f:Async context manager
asyncio.sleep(1)Non-blocking sleep
asyncio.Queue()Async producer-consumer queue
Decorators & Metaclasses
10 commands@functools.wraps(fn)Preserve wrapped fn metadata
@functools.lru_cache(maxsize=128)Memoize function results
@functools.cacheUnbounded cache (3.9+)
@contextmanagerTurn generator into context mgr
@classmethod / @staticmethodClass-level methods
@abstractmethodForce subclass implementation
@overloadType-hint multiple signatures
type(name, bases, dict)Create class dynamically
class Meta(type):Define metaclass
class Cls(metaclass=Meta):Use metaclass
Testing (pytest)
10 commandspip install pytestInstall pytest
def test_add():Test function (prefix test_)
assert result == expectedBasic assertion
pytest.raises(ValueError)Expect exception
@pytest.fixtureSetup/teardown helper
@pytest.mark.parametrize('a,b', [...])Parameterized tests
pytest -vVerbose output
pytest -k 'test_name'Run specific test
pytest --cov=srcCoverage report
monkeypatch.setattr(obj, 'attr', val)Mock attributes
Advanced Data Structures
10 commandsfrom heapq import heappush, heappopMin-heap (priority queue)
from collections import dequeDouble-ended queue (O(1) both ends)
from collections import OrderedDictInsertion-ordered dict
from collections import namedtupleLightweight immutable class
from dataclasses import dataclass, fieldAuto-generated class methods
from enum import Enum, autoEnumeration type
from typing import TypeVar, GenericGeneric types
frozenset({1, 2, 3})Immutable set (hashable)
from bisect import insort, bisect_leftSorted list operations
from itertools import chain, product, permutationsCombinatorics
Performance & Profiling
10 commandspython -m cProfile script.pyProfile entire script
from line_profiler import profileLine-by-line profiler
import timeit; timeit.timeit(fn, number=1000)Benchmark function
sys.getsizeof(obj)Object memory size
__slots__ = ['x', 'y']Reduce instance memory 40%
from functools import reduceFold/reduce a sequence
from operator import itemgetterFast key function for sort
from concurrent.futures import ThreadPoolExecutorThread pool
from concurrent.futures import ProcessPoolExecutorProcess pool
from multiprocessing import PoolParallel map
Type Hints (Advanced)
10 commandsx: int = 10Basic type annotation
def fn(x: str) -> bool:Function signature
Optional[int]int | None
Union[int, str]int or str
list[dict[str, Any]]Nested generic (3.9+)
Literal['a', 'b']Exact value type
TypeAlias = dict[str, list[int]]Type alias
Callable[[int], str]Function type
ProtocolStructural subtyping (duck typing)
mypy script.pyStatic type checker