Python Cheat Sheet
Data Structures
Section titled “Data Structures”lst = [1, 2, 3]lst.append(4) # Add to endlst.insert(0, 0) # Insert at indexlst.extend([5, 6]) # Add multiplelst.pop() # Remove lastlst.pop(0) # Remove at indexlst.remove(3) # Remove first occurrencelst[1:3] # Slice [2, 3]lst[::-1] # Reversesorted(lst, key=len) # Sort with keyDictionaries
Section titled “Dictionaries”d = {'a': 1, 'b': 2}d.get('c', 0) # Get with defaultd.setdefault('c', 3) # Set if missingd.update({'d': 4}) # Merged.pop('a') # Remove and returnd.keys(), d.values(), d.items(){k: v for k, v in d.items() if v > 1} # Comprehensions = {1, 2, 3}s.add(4)s.discard(2) # Remove if present (no error)s.remove(3) # Remove (raises KeyError if missing)s1 | s2 # Unions1 & s2 # Intersections1 - s2 # Differences1 ^ s2 # Symmetric differenceComprehensions
Section titled “Comprehensions”[x**2 for x in range(10)] # List{x: x**2 for x in range(10)} # Dict{x for x in range(10)} # Set(x**2 for x in range(10)) # Generator[x for x in items if x > 0] # Filter[x if x > 0 else 0 for x in items] # ConditionalString Operations
Section titled “String Operations”s = "hello world"s.split() # ['hello', 'world']s.split(',') # Split on delimiter'-'.join(['a', 'b']) # 'a-b's.strip() # Remove whitespaces.replace('o', '0') # Replaces.startswith('hello')s.endswith('world')f"value: {x:.2f}" # f-string formattingFile Operations
Section titled “File Operations”# Readingwith open('file.txt', 'r') as f: content = f.read() # Entire file lines = f.readlines() # List of lines
# Writingwith open('file.txt', 'w') as f: f.write('text') f.writelines(['a', 'b'])
# JSONimport jsondata = json.load(open('file.json'))json.dump(data, open('out.json', 'w'), indent=2)Functions
Section titled “Functions”def func(a, b, *args, **kwargs): """Docstring""" return a + b
# Lambdafn = lambda x, y: x + y
# Decoratorsdef decorator(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper
@decoratordef my_func(): passClasses
Section titled “Classes”class MyClass: class_var = 0
def __init__(self, value): self.value = value
def method(self): return self.value
@classmethod def from_string(cls, s): return cls(int(s))
@staticmethod def utility(): pass
@property def computed(self): return self.value * 2
# Dataclassesfrom dataclasses import dataclass
@dataclassclass Point: x: float y: float z: float = 0.0Error Handling
Section titled “Error Handling”try: risky_operation()except ValueError as e: print(f"Error: {e}")except (TypeError, KeyError): passexcept Exception as e: raise RuntimeError("Failed") from eelse: print("Success")finally: cleanup()Itertools & Functools
Section titled “Itertools & Functools”from itertools import chain, groupby, islice, cycle, permutations, combinationsfrom functools import reduce, partial, lru_cache
chain([1,2], [3,4]) # Flatten iterablesgroupby(items, key=lambda x: x[0]) # Group by keyislice(iterable, 5, 10) # Slice iteratorcombinations('ABC', 2) # ('A','B'), ('A','C'), ('B','C')permutations('ABC', 2) # All orderings
@lru_cache(maxsize=128)def expensive(n): return n ** 2Collections
Section titled “Collections”from collections import defaultdict, Counter, deque, namedtuple
dd = defaultdict(list)dd['key'].append(1)
counter = Counter(['a', 'a', 'b'])counter.most_common(2)
dq = deque([1, 2, 3])dq.appendleft(0)dq.popleft()
Point = namedtuple('Point', ['x', 'y'])Type Hints
Section titled “Type Hints”from typing import List, Dict, Optional, Union, Callable, TypeVar, Generic
def greet(name: str) -> str: return f"Hello, {name}"
def process(items: List[int]) -> Dict[str, int]: pass
def maybe(x: Optional[str] = None) -> Union[str, int]: pass
T = TypeVar('T')def first(items: List[T]) -> T: return items[0]Context Managers
Section titled “Context Managers”from contextlib import contextmanager
@contextmanagerdef managed_resource(): resource = acquire() try: yield resource finally: release(resource)
with managed_resource() as r: use(r)Async/Await
Section titled “Async/Await”import asyncio
async def fetch(url): await asyncio.sleep(1) return "data"
async def main(): results = await asyncio.gather( fetch("url1"), fetch("url2"), )
asyncio.run(main())Common Patterns
Section titled “Common Patterns”# Enumerate with indexfor i, item in enumerate(items): print(i, item)
# Zip parallel iterationfor a, b in zip(list1, list2): print(a, b)
# Dict from two listsdict(zip(keys, values))
# Flatten nested list[x for sublist in nested for x in sublist]
# Get or create patternvalue = cache.setdefault(key, compute_value())
# Safe dictionary accessvalue = data.get('key', {}).get('nested', default)See Also
Section titled “See Also”- Python Lesson Plan — 8 lessons from basics to async
- Testing — pytest commands and patterns
- Debugging — pdb, py-spy, flame graphs
- Learning a Language — Phases, techniques, anti-patterns
- Performance Profiling
- Python CLI
- Regex