DEV Community

Apaksh
Apaksh

Posted on

The Python Cheat Sheet You'll Actually Use

We all do it. We've written Python for years, and we still Google "python string format" or "how to sort a dictionary" at least once a week. No shame in it -- but what if you had everything in one place? This is the Python cheat sheet I keep pinned next to my monitor. It covers Python 3.10+ and includes the stuff you actually use, not the obscure corner cases you'll never need.

Data Types & Variables

# Core Types
x: int        = 42
y: float      = 3.14
z: complex    = 2 + 3j
s: str        = "hello"
b: bool       = True          # True / False
n: None       = None

# Type Checking & Conversion
type(x)                        # <class 'int'>
isinstance(x, int)             # True
isinstance(x, (int, float))    # True -- checks multiple
int("42"), float("3.14")       # parse from string
str(42), bool(0)               # 0 -> False, anything else -> True
Enter fullscreen mode Exit fullscreen mode

Type Quick Reference

  • int -- Immutable, not ordered
  • float -- Immutable, not ordered
  • str -- Immutable, ordered, allows duplicates
  • list -- Mutable, ordered, allows duplicates
  • tuple -- Immutable, ordered, allows duplicates
  • set -- Mutable, unordered, no duplicates
  • dict -- Mutable, ordered (insertion order since 3.7), keys unique
  • bytes -- Immutable, ordered, allows duplicates

Strings

s = "Hello, World!"

# Slicing  [start:stop:step]
s[0]        # 'H'
s[-1]       # '!'
s[0:5]      # 'Hello'
s[::-1]     # '!dlroW ,olleH'  -- reverse

# Common Methods
s.upper()           # 'HELLO, WORLD!'
s.lower()           # 'hello, world!'
s.strip()           # strips whitespace
s.replace("o","0")  # 'Hell0, W0rld!'
s.split(", ")       # ['Hello', 'World!']
s.startswith("He")  # True
s.find("World")     # 7  (-1 if not found)
s.count("l")        # 3
", ".join(["a","b","c"])  # 'a, b, c'

# f-Strings (use these -- fast & readable)
name, price = "Apple", 1.5
f"{name!r}"             # "'Apple'"  (repr)
f"{price:.2f}"          # '1.50'
f"{1000000:,}"          # '1,000,000'
f"{0.85:.1%}"           # '85.0%'
Enter fullscreen mode Exit fullscreen mode

Lists

lst = [3, 1, 4, 1, 5, 9, 2, 6]

# Mutation
lst.append(7)            # add to end
lst.extend([8, 9])       # add multiple
lst.insert(0, 0)         # insert at index
lst.remove(1)            # removes FIRST occurrence
lst.pop()                # remove & return last
lst.pop(0)               # remove & return at index

# Sorting
lst.sort()                          # in-place ascending
lst.sort(reverse=True)              # in-place descending
sorted(lst)                         # returns NEW list

# Unpacking
a, b, *rest = [1, 2, 3, 4, 5]   # a=1, b=2, rest=[3,4,5]

# zip / enumerate
for i, v in enumerate(lst, start=1): ...
for a, b in zip(list1, list2): ...
Enter fullscreen mode Exit fullscreen mode

Dictionaries

d = {"name": "Ada", "age": 36}

d["name"]                    # 'Ada'  (KeyError if missing)
d.get("name")                # 'Ada'  (None if missing)
d.get("x", "default")       # 'default'
d["city"] = "London"         # add/update
d.pop("age", None)           # remove & return (safe)

# Merging (Python 3.9+)
merged = d1 | d2             # new merged dict
d1 |= d2                     # update d1 in-place

# defaultdict
from collections import defaultdict
dd = defaultdict(list)
dd["a"].append(1)            # no KeyError

# Counter
from collections import Counter
c = Counter("mississippi")   # Counter({'s':4,'i':4,'p':2,'m':1})

# Dict comprehension
squares = {x: x**2 for x in range(6)}
Enter fullscreen mode Exit fullscreen mode

Sets

s = {1, 2, 3, 4}
t = {3, 4, 5, 6}

s | t    # union          {1,2,3,4,5,6}
s & t    # intersection   {3,4}
s - t    # difference     {1,2}
s ^ t    # symmetric diff {1,2,5,6}
3 in s   # True  (O(1) avg)
Enter fullscreen mode Exit fullscreen mode

Comprehensions

# List Comprehension
[x**2 for x in range(10)]
[x for x in range(20) if x % 2 == 0]

# Nested
matrix = [[1,2,3],[4,5,6]]
flat = [n for row in matrix for n in row]  # [1,2,3,4,5,6]

# Dict Comprehension
{k: v for k, v in zip("abc", [1,2,3])}

# Generator Expression (lazy -- memory efficient)
total = sum(x**2 for x in range(1000000))  # no list created!
Enter fullscreen mode Exit fullscreen mode

Control Flow

# match / case (Python 3.10+)
match command:
    case "quit":
        quit()
    case "go" | "move":
        move()
    case {"action": action, "target": target}:
        do(action, target)
    case _:
        print("unknown")

# for / else  (else runs if loop didn't break)
for item in lst:
    if condition(item):
        break
else:
    print("no break occurred")
Enter fullscreen mode Exit fullscreen mode

Functions

def greet(name: str, greeting: str = "Hello") -> str:
    return f"{greeting}, {name}!"

# *args and **kwargs
def func(*args, **kwargs):
    print(args)    # tuple
    print(kwargs)  # dict

# Keyword-only args (after *)
def connect(host, *, port=80, ssl=True): ...

# Lambda
square = lambda x: x**2
sorted(data, key=lambda d: d["age"])
Enter fullscreen mode Exit fullscreen mode

Decorators

import functools

def my_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print("before")
        result = func(*args, **kwargs)
        print("after")
        return result
    return wrapper

@my_decorator
def say_hi(): print("hi")

# Common Built-in Decorators
@staticmethod          # no self/cls
@classmethod           # cls instead of self
@property              # getter
@functools.lru_cache(maxsize=128)   # memoization
Enter fullscreen mode Exit fullscreen mode

Generators & Iterators

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for x in countdown(3):   # 3, 2, 1
    print(x)

# itertools (extremely useful)
import itertools as it
it.chain([1,2],[3,4])     # 1,2,3,4
it.islice(gen, 5)         # first 5 items
it.product("AB", repeat=2)# AA AB BA BB
it.permutations("ABC", 2) # all 2-perms
it.combinations("ABC", 2) # all 2-combos
Enter fullscreen mode Exit fullscreen mode

Classes & OOP

# Dataclass (Python 3.7+) -- auto __init__, __repr__, __eq__
from dataclasses import dataclass, field

@dataclass
class Point:
    x: float
    y: float
    z: float = 0.0
    tags: list = field(default_factory=list)

@dataclass(frozen=True)   # immutable + hashable
class Color:
    r: int; g: int; b: int
Enter fullscreen mode Exit fullscreen mode

Exceptions

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
except (TypeError, ValueError) as e:
    print(f"Type/Value error: {e}")
else:
    print("no exception!")
finally:
    print("always runs")

# Custom Exceptions
class AppError(Exception):
    def __init__(self, message, code=None):
        super().__init__(message)
        self.code = code
Enter fullscreen mode Exit fullscreen mode

File I/O

# Reading
with open("file.txt", "r", encoding="utf-8") as f:
    content = f.read()

# Writing
with open("out.txt", "w", encoding="utf-8") as f:
    f.write("Hello\n")

# pathlib (prefer over os.path)
from pathlib import Path
p = Path("data/file.txt")
p.exists()          # True/False
p.read_text()       # read entire file
p.write_text("hi")  # write entire file
p / "sub" / "x.py"  # join paths with /
list(p.parent.glob("*.txt"))     # glob
Enter fullscreen mode Exit fullscreen mode

Context Managers

from contextlib import contextmanager

@contextmanager
def timer():
    import time
    start = time.perf_counter()
    try:
        yield
    finally:
        print(f"Elapsed: {time.perf_counter()-start:.3f}s")

with timer():
    heavy_computation()
Enter fullscreen mode Exit fullscreen mode

Dates & Times

from datetime import datetime, date, timedelta

now = datetime.now()
today = date.today()

# Formatting / Parsing
dt.strftime("%Y-%m-%d %H:%M:%S")
datetime.strptime("2024-01-15", "%Y-%m-%d")

# Arithmetic
tomorrow = today + timedelta(days=1)
delta = dt2 - dt1
delta.total_seconds()
Enter fullscreen mode Exit fullscreen mode

Testing

# pytest (preferred)
def test_add():
    assert add(2, 3) == 5

import pytest

@pytest.fixture
def sample_data():
    return [1, 2, 3]

@pytest.mark.parametrize("a,b,expected", [
    (1, 2, 3),
    (0, 0, 0),
    (-1, 1, 0),
])
def test_add_parametrized(a, b, expected):
    assert a + b == expected
Enter fullscreen mode Exit fullscreen mode

If you found this useful, share it with a colleague who needs it. Subscribe for more developer resources every week.


Want the full resource?

Python Cheat Sheet — $6.99 on Gumroad

Get the complete, downloadable version. Perfect for bookmarking, printing, or sharing with your team.

Get it now on Gumroad →


If you found this useful, drop a ❤️ and follow for more developer resources every week.

Top comments (0)