x = 10 Variable assignment
x, y = 1, 2 Multiple assignment
type(x) Get type of variable
int(x) / float(x) / str(x) Type casting
print(f"Hello {name}") F-string formatting
input("Enter: ") Read user input
if x > 0:
pass
elif x == 0:
pass
else:
pass If/elif/else conditional
for i in range(10): For loop with range
while condition: While loop
x if condition else y Ternary expression
try:
...
except Exception as e:
...
finally:
... Try/except/finally
assert condition, "message" Assertion check
s.upper() / s.lower() Convert to upper/lower case
s.strip() Remove leading/trailing whitespace
s.split(",") Split string into list
",".join(lst) Join list into string
s.replace("old", "new") Replace substring
s.startswith("prefix") Check if string starts with
s.find("sub") Find substring index (-1 if not found)
s[1:5] Slice string (index 1 to 4)
s.isdigit() / s.isalpha() Check if digits/letters only
s.zfill(5) Pad string with zeros
lst = [1, 2, 3] Create a list
lst.append(4) Add item to end
lst.insert(0, "first") Insert at index
lst.pop() / lst.pop(0) Remove last / at index
lst.remove(value) Remove first occurrence of value
lst.sort() / sorted(lst) Sort in-place / return sorted copy
lst.reverse() Reverse list in-place
lst[1:3] Slice list
len(lst) Get list length
item in lst Check if item exists in list
lst.index(value) Get index of first occurrence
list(zip(a, b)) Zip two lists together
lst.extend([4, 5]) Extend list with another list
d = {"key": "value"} Create a dictionary
d["key"] / d.get("key", default) Access value (with optional default)
d.keys() / d.values() / d.items() Get keys, values, or key-value pairs
d.update({"k2": "v2"}) Merge another dict
d.pop("key") Remove and return value by key
"key" in d Check if key exists
d | other_dict Merge dicts (Python 3.9+)
dict.fromkeys(["a","b"], 0) Create dict with default values
def fn(x, y=10): Function with default parameter
def fn(*args, **kwargs): Variadic arguments
lambda x: x * 2 Anonymous function
def fn() -> int: Function with return type hint
@decorator
def fn(): Apply decorator to function
map(fn, iterable) Apply function to each item
filter(fn, iterable) Filter items by function
functools.reduce(fn, iterable) Reduce iterable to single value
[x**2 for x in range(10)] List comprehension
[x for x in lst if x > 0] List comprehension with filter
{k: v for k, v in items} Dict comprehension
{x for x in lst} Set comprehension
(x**2 for x in range(10)) Generator expression (lazy)
class Dog:
def __init__(self, name):
self.name = name Class with constructor
class Cat(Animal): Class inheritance
@property
def name(self): Property getter
@staticmethod
def create(): Static method (no self)
@classmethod
def from_dict(cls, d): Class method (cls instead of self)
def __str__(self): String representation
def __len__(self): Custom len() behavior
@dataclass
class Point:
x: float
y: float Dataclass (auto __init__, __repr__)
with open("f.txt") as f:
text = f.read() Read entire file
with open("f.txt", "w") as f:
f.write("text") Write to file
with open("f.txt") as f:
for line in f: Read file line by line
import json
json.loads(s) / json.dumps(obj) Parse / stringify JSON
import csv
csv.reader(file) Read CSV file
from pathlib import Path
Path("dir").mkdir(exist_ok=True) Create directory
Path("file.txt").exists() Check if file exists
Path("file.txt").read_text() Read file as string (pathlib)
import os Import entire module
from os import path Import specific item
import numpy as np Import with alias
pip install package Install package with pip
pip freeze > requirements.txt Export dependencies
python -m venv .venv Create virtual environment
if __name__ == "__main__": Run only when executed directly
Python Cheat Sheet — Quick Reference & Syntax Guide
Guido van Rossum released Python 1.0 in 1994, and although the language has since gained type hints, f-strings, pattern matching and the walrus operator, the core grammar — significant whitespace, duck typing, everything-is-an-object — has barely shifted in three decades. The reference below covers 75+ snippets across basics, strings, lists, dicts, functions, comprehensions, classes, file I/O and modules. Most trouble in real scripts doesn't come from forgetting syntax. It comes from quirks that look ordinary but bite. A mutable default argument like `def f(x=[])` is evaluated once at definition time, so every call without an `x` shares the same list — a classic accidental cache. `is` compares identity and `==` compares value, and `a is b` happens to return `True` for small integers by sheer luck of the runtime, then quietly fails on larger ones. Indentation is part of the grammar, so mixing tabs and four-space groups raises `IndentationError` even when the file looks aligned. These are the snippets reached for when debugging that — the default-arg trap, identity versus equality, the comprehension that filters and maps in one pass.
Common pitfalls in Python
A few patterns earn their place on the first screen of any Python file. `if __name__ == "__main__":` guards the entry point so the script can be imported without running, which matters the moment a second file wants to reuse one of its functions. `with open(path) as f:` closes the file on every exit path including exceptions, replacing a `try`/`finally` that nobody writes correctly. F-strings `f"value: {x:.2f}"` carry both formatting and inline expressions, replacing `%`-style formatting and `.format()` for almost every case. List comprehensions like `[x*2 for x in xs if x > 0]` fold a `map` and a `filter` into one line and avoid building an intermediate list. And `pathlib.Path` returns a richer object than the legacy `os.path` strings — `Path("f.txt").read_text()` is one call where the old way took three. The cheatsheet groups all of this into basics, strings, lists, dicts, functions, comprehensions, classes, files and modules so the right section is one click away.
- 75+ practical Python snippets
- 9 categories from basics to modules
- Search across code and descriptions
- Filter by category
- One-click copy to clipboard
- Covers Python 3.9+ features
Free. No signup. Your inputs stay in your browser. Ads via Google AdSense (consent required).