Skip to content

Python Cheat Sheet — Complete Reference (75+ snippets, 2026)

Last verified May 2026 — runs in your browser
Python Cheatsheet
x = 10

Variable assignment

Basics
x, y = 1, 2

Multiple assignment

Basics
type(x)

Get type of variable

Basics
int(x) / float(x) / str(x)

Type casting

Basics
print(f"Hello {name}")

F-string formatting

Basics
input("Enter: ")

Read user input

Basics
if x > 0: pass elif x == 0: pass else: pass

If/elif/else conditional

Basics
for i in range(10):

For loop with range

Basics
while condition:

While loop

Basics
x if condition else y

Ternary expression

Basics
try: ... except Exception as e: ... finally: ...

Try/except/finally

Basics
assert condition, "message"

Assertion check

Basics
s.upper() / s.lower()

Convert to upper/lower case

Strings
s.strip()

Remove leading/trailing whitespace

Strings
s.split(",")

Split string into list

Strings
",".join(lst)

Join list into string

Strings
s.replace("old", "new")

Replace substring

Strings
s.startswith("prefix")

Check if string starts with

Strings
s.find("sub")

Find substring index (-1 if not found)

Strings
s[1:5]

Slice string (index 1 to 4)

Strings
s.isdigit() / s.isalpha()

Check if digits/letters only

Strings
s.zfill(5)

Pad string with zeros

Strings
lst = [1, 2, 3]

Create a list

Lists
lst.append(4)

Add item to end

Lists
lst.insert(0, "first")

Insert at index

Lists
lst.pop() / lst.pop(0)

Remove last / at index

Lists
lst.remove(value)

Remove first occurrence of value

Lists
lst.sort() / sorted(lst)

Sort in-place / return sorted copy

Lists
lst.reverse()

Reverse list in-place

Lists
lst[1:3]

Slice list

Lists
len(lst)

Get list length

Lists
item in lst

Check if item exists in list

Lists
lst.index(value)

Get index of first occurrence

Lists
list(zip(a, b))

Zip two lists together

Lists
lst.extend([4, 5])

Extend list with another list

Lists
d = {"key": "value"}

Create a dictionary

Dicts
d["key"] / d.get("key", default)

Access value (with optional default)

Dicts
d.keys() / d.values() / d.items()

Get keys, values, or key-value pairs

Dicts
d.update({"k2": "v2"})

Merge another dict

Dicts
d.pop("key")

Remove and return value by key

Dicts
"key" in d

Check if key exists

Dicts
d | other_dict

Merge dicts (Python 3.9+)

Dicts
dict.fromkeys(["a","b"], 0)

Create dict with default values

Dicts
def fn(x, y=10):

Function with default parameter

Functions
def fn(*args, **kwargs):

Variadic arguments

Functions
lambda x: x * 2

Anonymous function

Functions
def fn() -> int:

Function with return type hint

Functions
@decorator def fn():

Apply decorator to function

Functions
map(fn, iterable)

Apply function to each item

Functions
filter(fn, iterable)

Filter items by function

Functions
functools.reduce(fn, iterable)

Reduce iterable to single value

Functions
[x**2 for x in range(10)]

List comprehension

Comprehensions
[x for x in lst if x > 0]

List comprehension with filter

Comprehensions
{k: v for k, v in items}

Dict comprehension

Comprehensions
{x for x in lst}

Set comprehension

Comprehensions
(x**2 for x in range(10))

Generator expression (lazy)

Comprehensions
class Dog: def __init__(self, name): self.name = name

Class with constructor

Classes
class Cat(Animal):

Class inheritance

Classes
@property def name(self):

Property getter

Classes
@staticmethod def create():

Static method (no self)

Classes
@classmethod def from_dict(cls, d):

Class method (cls instead of self)

Classes
def __str__(self):

String representation

Classes
def __len__(self):

Custom len() behavior

Classes
@dataclass class Point: x: float y: float

Dataclass (auto __init__, __repr__)

Classes
with open("f.txt") as f: text = f.read()

Read entire file

Files
with open("f.txt", "w") as f: f.write("text")

Write to file

Files
with open("f.txt") as f: for line in f:

Read file line by line

Files
import json json.loads(s) / json.dumps(obj)

Parse / stringify JSON

Files
import csv csv.reader(file)

Read CSV file

Files
from pathlib import Path Path("dir").mkdir(exist_ok=True)

Create directory

Files
Path("file.txt").exists()

Check if file exists

Files
Path("file.txt").read_text()

Read file as string (pathlib)

Files
import os

Import entire module

Modules
from os import path

Import specific item

Modules
import numpy as np

Import with alias

Modules
pip install package

Install package with pip

Modules
pip freeze > requirements.txt

Export dependencies

Modules
python -m venv .venv

Create virtual environment

Modules
if __name__ == "__main__":

Run only when executed directly

Modules
Showing 79 of 79 snippets

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).