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
Free Online Python Cheatsheet
A searchable, filterable Python quick reference. Covers basics, strings, lists, dictionaries, functions, classes, comprehensions, file I/O, and common modules. Copy any snippet with one click.
About this cheatsheet
A comprehensive Python cheatsheet covering the most commonly used patterns and syntax.
- 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
100% free. No signup required. No data collected or sent anywhere.