Python Cheat Sheet
Quick reference for Python syntax, data structures, string methods, list comprehensions, file I/O, and common patterns. All essentials on one page.
Variables & Data Types
String Methods
List Operations
Dictionary Operations
Control Flow
Functions & Classes
File I/O & Common Modules
Variables & Data Types
| x = 10 | Integer |
| y = 3.14 | Float |
| name = "hello" | String |
| is_valid = True | Boolean (True/False) |
| items = [1, 2, 3] | List (mutable, ordered) |
| coords = (10, 20) | Tuple (immutable, ordered) |
| ages = {"alice": 30} | Dictionary (key-value pairs) |
| unique = {1, 2, 3} | Set (unique values, unordered) |
| x = None | Null/nothing value |
| type(x) | Check type of variable |
String Methods
| s.upper() / s.lower() | Convert case |
| s.strip() | Remove leading/trailing whitespace |
| s.split(",") | Split into list by delimiter |
| ",".join(list) | Join list into string |
| s.replace("old", "new") | Replace substring |
| s.startswith("http") | Check prefix (returns bool) |
| s.find("sub") | Index of substring (-1 if not found) |
| f"Hello {name}" | f-string formatting (Python 3.6+) |
| s[1:5] | Slice from index 1 to 4 |
| len(s) | String length |
List Operations
| lst.append(x) | Add item to end |
| lst.insert(i, x) | Insert at index i |
| lst.pop() / lst.pop(i) | Remove last / at index |
| lst.remove(x) | Remove first occurrence of x |
| lst.sort() / sorted(lst) | Sort in-place / return new sorted |
| lst.reverse() | Reverse in-place |
| lst[::2] | Every other element (step slice) |
| [x**2 for x in lst] | List comprehension |
| [x for x in lst if x > 0] | Filtered list comprehension |
| list(zip(a, b)) | Pair elements from two lists |
Dictionary Operations
| d[key] / d.get(key, default) | Access value (KeyError vs default) |
| d[key] = value | Set/update value |
| d.keys() / d.values() / d.items() | Views of keys, values, pairs |
| d.pop(key) | Remove and return value |
| d.update(other_dict) | Merge another dict |
| {**d1, **d2} | Merge dicts (Python 3.5+) |
| d1 | d2 | Merge dicts (Python 3.9+) |
| {k: v for k, v in items} | Dictionary comprehension |
Control Flow
| if x > 0: ... elif: ... else: | Conditional branching |
| for item in iterable: | For loop over iterable |
| for i, v in enumerate(lst): | Loop with index |
| while condition: | While loop |
| break / continue | Exit loop / skip to next iteration |
| x if cond else y | Ternary expression |
| match value: case 1: ... | Pattern matching (Python 3.10+) |
| try: ... except Error as e: | Exception handling |
| with open(f) as file: | Context manager (auto-close) |
Functions & Classes
| def func(a, b=10): | Function with default argument |
| def func(*args, **kwargs): | Variable positional & keyword args |
| lambda x: x * 2 | Anonymous function |
| @decorator | Function decorator syntax |
| -> int | Return type hint |
| class Dog: ... | Class definition |
| def __init__(self, name): | Constructor |
| super().__init__() | Call parent class constructor |
| @staticmethod / @classmethod | Static and class methods |
| @property | Getter property decorator |
File I/O & Common Modules
| open("file.txt", "r").read() | Read entire file |
| open("file.txt", "w").write(data) | Write to file (overwrite) |
| json.loads(s) / json.dumps(obj) | Parse/serialize JSON |
| os.path.join(a, b) | Join path components |
| pathlib.Path("dir") / "file" | Modern path handling |
| import re; re.findall(pattern, s) | Regex find all matches |
| from datetime import datetime | Date/time module |
| import sys; sys.argv | Command line arguments |
| pip install package | Install package from PyPI |
| python -m venv env | Create virtual environment |