Cheat Sheet

Python Cheat Sheet

Quick reference for Python syntax, list/dict operations, file I/O, and common patterns

Data Types

# Basic types
s = "hello"          # str
n = 42               # int
f = 3.14             # float
b = True             # bool
x = None             # NoneType
# Collections
lst = [1, 2, 3]      # list
tup = (1, 2, 3)      # tuple (immutable)
dct = {"a": 1}       # dict
st = {1, 2, 3}       # set (unique values)

List Operations

lst = [1, 2, 3, 4, 5]
lst.append(6)              # [1,2,3,4,5,6]
lst.extend([7, 8])         # [1,2,3,4,5,6,7,8]
lst.insert(0, 0)           # Insert at index
lst.remove(3)              # Remove first match
lst.pop()                  # Remove & return last
lst.pop(0)                 # Remove & return at index
lst[1:3]                   # Slice [2,3]
lst[::-1]                  # Reverse
[x*2 for x in lst]         # List comprehension

Dict Operations

d = {"name": "Alice", "age": 30}
d["email"] = "a@b.com"     # Insert/update
d.get("phone", "N/A")      # Safe get with default
d.keys()                   # Keys view
d.values()                 # Values view
d.items()                  # (key, value) pairs
del d["age"]               # Delete key
{**d, "role": "admin"}     # Merge
{k: v for k, v in d.items() if v}

String Methods

s = "hello world"
s.upper()                  # HELLO WORLD
s.lower()                  # hello world
s.strip()                  # Remove whitespace
s.split(",")               # Split into list
",".join(["a", "b"])       # Join list
s.replace("world", "there")
s.startswith("hello")
s.endswith("world")
s.find("world")            # Index or -1

File I/O

# Read
with open("file.txt") as f:
    content = f.read()                    # Whole file
    lines = f.readlines()                 # List of lines
    for line in f:                        # Line by line
        print(line.strip())
# Write
with open("file.txt", "w") as f:
    f.write("hello\n")
    f.writelines(["line1\n", "line2\n"])
# Append
with open("file.txt", "a") as f:
    f.write("more data\n")

Error Handling

try:
    result = risky_operation()
except ValueError as e:
    print(f"Bad value: {e}")
except (IOError, OSError) as e:
    print(f"IO error: {e}")
except Exception as e:
    print(f"Unexpected: {e}")
else:
    print("No error occurred")
finally:
    print("Always runs")

Common One-Liners

sorted(lst, key=lambda x: x["name"])
filter(lambda x: x > 0, lst)
map(str.upper, lst)
list(zip(names, ages))                        # Pair lists
enumerate(items)                              # (index, item)
any(x > 10 for x in lst)                      # True if any match
all(x > 0 for x in lst)                       # True if all match
set(lst)                                      # Deduplicate
isinstance(x, (int, float))                   # Type check

Virtual Environments

python -m venv venv
source venv/bin/activate
pip install requests
pip freeze > requirements.txt
pip install -r requirements.txt