Python Cheat Sheet

Essential Python syntax and concepts. Variables, data types, strings, lists, dictionaries, functions, classes, file I/O, and standard library.

Basics & Types

# Variables (no declaration keyword needed)
name = "Alice"
age = 30
pi = 3.14
is_active = True
nothing = None
TypeExampleCheck
int42isinstance(x, int)
float3.14isinstance(x, float)
str"hello"isinstance(x, str)
boolTrue / Falseisinstance(x, bool)
list[1, 2, 3]isinstance(x, list)
tuple(1, 2, 3)isinstance(x, tuple)
dict{"a": 1}isinstance(x, dict)
set{1, 2, 3}isinstance(x, set)
NoneTypeNonex is None

Type Conversion

int("42")      # 42
float("3.14")  # 3.14
str(42)        # "42"
bool(0)        # False
bool("")       # False
list("abc")    # ["a", "b", "c"]
tuple([1,2])   # (1, 2)
set([1,1,2])   # {1, 2}

Operators

OperatorDescription
+ - * /Arithmetic (/ always returns float)
//Floor division (integer result)
%Modulo (remainder)
**Exponent (2**3 = 8)
== !=Equality / inequality (value)
is is notIdentity (same object)
and or notLogical operators
in not inMembership test
:=Walrus operator (assign + return)

Strings

Method / SyntaxDescription
f"Hello {name}"f-string (formatted string literal)
f"{price:.2f}"Format float to 2 decimal places
len(s)String length
s.upper()Uppercase
s.lower()Lowercase
s.title()Title Case
s.strip()Remove whitespace from both ends
s.lstrip() / s.rstrip()Remove whitespace from left/right
s.split(",")Split into list
",".join(list)Join list into string
s.replace("a", "b")Replace all occurrences
s.find("sub")Index of substring (-1 if not found)
s.count("a")Count occurrences
s.startswith("He")Check prefix
s.endswith(".py")Check suffix
s.isdigit()Check if all digits
s.isalpha()Check if all alphabetic
s.zfill(5)Pad with zeros: "42" → "00042"
s[0:5]Slice (start:end)
s[::-1]Reverse string
"sub" in sCheck if substring exists
# Multi-line strings
text = """Line 1
Line 2
Line 3"""

# Raw strings (no escape processing)
path = r"C:\Users\name\file"

Lists

Method / SyntaxDescription
lst.append(x)Add item to end
lst.insert(i, x)Insert at index
lst.extend([4,5])Add multiple items
lst.remove(x)Remove first occurrence of x
lst.pop()Remove and return last item
lst.pop(i)Remove and return item at index
lst.clear()Remove all items
lst.index(x)Index of first occurrence
lst.count(x)Count occurrences
lst.sort()Sort in place
lst.sort(reverse=True)Sort descending
lst.sort(key=len)Sort by key function
sorted(lst)Return new sorted list
lst.reverse()Reverse in place
lst.copy()Shallow copy
len(lst)Length
min(lst) / max(lst)Min / max value
sum(lst)Sum of all elements
x in lstMembership test

Slicing

lst = [0, 1, 2, 3, 4, 5]
lst[1:4]     # [1, 2, 3]       start:end
lst[:3]      # [0, 1, 2]       first 3
lst[3:]      # [3, 4, 5]       from index 3
lst[-2:]     # [4, 5]          last 2
lst[::-1]    # [5, 4, 3, 2, 1, 0]  reversed
lst[0:5:2]   # [0, 2, 4]       step=2

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

Dictionaries

Method / SyntaxDescription
d = {"a": 1, "b": 2}Create dictionary
d["a"]Access value (KeyError if missing)
d.get("a", default)Access with default (no error)
d["c"] = 3Add or update key
del d["a"]Delete key
d.pop("a", default)Remove key and return value
d.keys()View of keys
d.values()View of values
d.items()View of (key, value) tuples
d.update(other)Merge another dict
d | otherMerge dicts (Python 3.9+)
d |= otherUpdate in place (Python 3.9+)
"key" in dCheck if key exists
len(d)Number of keys
d.setdefault("k", [])Get or set default value
dict.fromkeys(keys, val)Create dict with default value
# Iterate
for key, value in d.items():
    print(f"{key}: {value}")

# Dict comprehension
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Sets & Tuples

# Sets — unordered, unique values
s = {1, 2, 3}
s.add(4)            # add element
s.discard(2)        # remove (no error if missing)
s.remove(3)         # remove (KeyError if missing)

# Set operations
a | b               # union
a & b               # intersection
a - b               # difference
a ^ b               # symmetric difference
a.issubset(b)       # True if a ⊆ b

# Tuples — immutable, ordered
t = (1, 2, 3)
t[0]                # 1
a, b, c = t         # unpacking
single = (1,)       # single-element tuple (note comma)

Control Flow

# If / elif / else
if x > 10:
    print("big")
elif x > 5:
    print("medium")
else:
    print("small")

# Ternary
result = "yes" if condition else "no"

# For loop
for i in range(5):           # 0, 1, 2, 3, 4
    print(i)

for i in range(2, 10, 2):   # 2, 4, 6, 8
    print(i)

for i, val in enumerate(lst):  # index + value
    print(i, val)

for a, b in zip(list1, list2):  # parallel iteration
    print(a, b)

# While loop
while count < 10:
    count += 1

# break, continue, else
for x in lst:
    if x == target:
        break
else:
    print("not found")  # runs if no break

# Match (Python 3.10+)
match command:
    case "start":
        start()
    case "stop":
        stop()
    case _:
        print("unknown")

Functions

# Basic function
def greet(name):
    return f"Hello, {name}!"

# Default parameters
def greet(name="World"):
    return f"Hello, {name}!"

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

# Lambda (anonymous function)
square = lambda x: x ** 2
sorted(lst, key=lambda x: x[1])

# Type hints
def add(a: int, b: int) -> int:
    return a + b

# Decorators
def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"Took {time.time() - start:.2f}s")
        return result
    return wrapper

@timer
def slow_fn():
    time.sleep(1)

# Generator
def count_up(n):
    i = 0
    while i < n:
        yield i
        i += 1

Built-in Functions

FunctionDescription
print()Print to stdout
len()Length of object
range(start, stop, step)Sequence of numbers
enumerate(iterable)Index + value pairs
zip(a, b)Pair elements from iterables
map(fn, iterable)Apply function to each element
filter(fn, iterable)Keep elements where fn is truthy
sorted(iterable, key=)Return new sorted list
reversed(iterable)Reverse iterator
any(iterable)True if any element is truthy
all(iterable)True if all elements are truthy
abs(x)Absolute value
round(x, n)Round to n decimal places
input("prompt")Read user input (string)
type(x)Type of object
dir(obj)List attributes/methods
help(obj)Built-in documentation

Classes

class Animal:
    # Class variable
    species = "Unknown"

    def __init__(self, name, sound):
        # Instance variables
        self.name = name
        self._sound = sound  # convention: "private"

    def speak(self):
        return f"{self.name} says {self._sound}"

    def __str__(self):
        return f"Animal({self.name})"

    def __repr__(self):
        return f"Animal('{self.name}', '{self._sound}')"

    @property
    def sound(self):
        return self._sound

    @staticmethod
    def is_animal(obj):
        return isinstance(obj, Animal)

    @classmethod
    def create_dog(cls, name):
        return cls(name, "Woof")

# Inheritance
class Dog(Animal):
    species = "Canine"

    def __init__(self, name):
        super().__init__(name, "Woof")

    def fetch(self, item):
        return f"{self.name} fetches {item}"

# Dataclass (Python 3.7+)
from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float
    z: float = 0.0

File I/O

# Read file
with open("file.txt", "r") as f:
    content = f.read()        # entire file as string
    lines = f.readlines()     # list of lines

# Read line by line (memory efficient)
with open("file.txt") as f:
    for line in f:
        print(line.strip())

# Write file
with open("file.txt", "w") as f:
    f.write("Hello\n")

# Append to file
with open("file.txt", "a") as f:
    f.write("More text\n")

# JSON
import json
data = json.loads(json_string)    # parse JSON string
json_str = json.dumps(data, indent=2)  # to JSON string

with open("data.json") as f:
    data = json.load(f)           # read JSON file

with open("data.json", "w") as f:
    json.dump(data, f, indent=2)   # write JSON file

# CSV
import csv
with open("data.csv") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"])
ModeDescription
"r"Read (default)
"w"Write (overwrites)
"a"Append
"x"Create (error if exists)
"rb" / "wb"Binary read/write

Comprehensions

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

# Dict comprehension
d = {k: v for k, v in zip(keys, values)}

# Set comprehension
unique = {x.lower() for x in words}

# Generator expression (lazy, memory efficient)
total = sum(x**2 for x in range(1000000))

# Nested comprehension
flat = [x for row in matrix for x in row]

# Conditional expression
labels = ["even" if x%2==0 else "odd" for x in range(5)]

Error Handling

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
except (TypeError, ValueError) as e:
    print(f"Error: {e}")
except Exception as e:
    print(f"Unexpected: {e}")
else:
    print("Success")      # runs if no exception
finally:
    print("Cleanup")      # always runs

# Raise exception
raise ValueError("Invalid input")

# Custom exception
class AppError(Exception):
    pass
ExceptionWhen
ValueErrorWrong value (e.g., int("abc"))
TypeErrorWrong type (e.g., "a" + 1)
KeyErrorMissing dict key
IndexErrorIndex out of range
FileNotFoundErrorFile doesn't exist
AttributeErrorMissing attribute/method
ImportErrorModule not found
ZeroDivisionErrorDivision by zero
StopIterationIterator exhausted

Standard Library Highlights

# os / pathlib — file system
from pathlib import Path
p = Path("dir/file.txt")
p.exists()  p.is_file()  p.is_dir()
p.read_text()  p.write_text("data")
p.parent  p.stem  p.suffix  p.name
list(Path(".").glob("*.py"))

# datetime
from datetime import datetime, timedelta
now = datetime.now()
formatted = now.strftime("%Y-%m-%d %H:%M")
parsed = datetime.strptime("2026-05-08", "%Y-%m-%d")
tomorrow = now + timedelta(days=1)

# collections
from collections import Counter, defaultdict, deque
Counter(["a","b","a"])  # Counter({'a': 2, 'b': 1})
dd = defaultdict(list)
dd["key"].append(1)     # auto-creates list

# itertools
from itertools import chain, product, combinations
list(chain([1,2], [3,4]))     # [1, 2, 3, 4]
list(combinations("abc", 2))  # [('a','b'), ('a','c'), ('b','c')]

# re — regex
import re
re.findall(r'\d+', "abc 123")   # ['123']
re.sub(r'\s+', ' ', text)         # collapse whitespace

# random
import random
random.randint(1, 10)      # random int 1-10
random.choice(lst)          # random element
random.shuffle(lst)         # shuffle in place
random.sample(lst, 3)       # 3 random elements