🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
Search courses…
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Python Cheatsheet — Quick Reference Guide

Python ReferenceCheatsheet🟢 Free Lesson

Advertisement

Python Cheatsheet — Quick Reference Guide

A comprehensive quick reference for Python syntax, common patterns, and essential standard library modules. Keep this handy for daily coding.


Variables & Types

x = 42              # int
y = 3.14            # float
s = "hello"         # str
b = True            # bool
n = None            # NoneType
l = [1, 2, 3]       # list (mutable)
t = (1, 2)          # tuple (immutable)
d = {"k": "v"}      # dict
s = {1, 2, 3}       # set
fs = frozenset([1])  # frozenset (immutable set)

Type Conversion

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

String Methods

"hello".upper()              # "HELLO"
"hello".lower()              # "hello"
"hello".title()              # "Hello"
"  hello  ".strip()          # "hello"
"hello world".split()        # ["hello", "world"]
"-".join(["a", "b", "c"])    # "a-b-c"
"hello".replace("l", "L")    # "heLLo"
"hello".find("ll")           # 2
"hello".startswith("he")     # True
"hello".endswith("lo")       # True
"hello123".isalnum()         # True
"123".isdigit()              # True
"hello".count("l")           # 2
f"Name: {name}, Age: {age}"  # f-string

String Formatting

# f-strings (Python 3.6+) — recommended
name, age = "Alice", 30
f"{name} is {age} years old"
f"{price:.2f}"  # "3.14"
f"{name:>10}"   # right-aligned
f"{name:<10}"   # left-aligned
f"{name:^10}"   # centered
f"{value:,}"    # "1,000,000"
f"{value:.2%}"  # "0.75" -> "75.00%"

# .format()
"{} is {}".format(name, age)
"{name} is {age}".format(name="Alice", age=30)

# % formatting (old style)
"%s is %d years old" % (name, age)

Regular Expressions

import re

re.search(r'\d+', 'abc123')     # Match object
re.findall(r'\d+', 'a1b2c3')    # ['1', '2', '3']
re.sub(r'\d', 'x', 'a1b2')     # 'axbx'
re.split(r'\s+', 'a b c')       # ['a', 'b', 'c']
re.match(r'^\d+$', '123')       # Match object
re.compile(r'\d+').findall('a1b2')  # Compiled pattern

List Operations

l = [1, 2, 3]
l.append(4)          # [1, 2, 3, 4]
l.insert(0, 0)       # [0, 1, 2, 3, 4]
l.extend([5, 6])     # [0, 1, 2, 3, 4, 5, 6]
l.pop()              # returns 6
l.pop(0)             # returns 0
l.remove(3)          # removes first 3
l.sort()             # in-place sort
l.reverse()          # in-place reverse
l.copy()             # shallow copy
l.index(2)           # index of first 2
l.count(1)           # occurrences of 1
l.clear()            # removes all elements

List Comprehensions

squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
matrix = [[i*3+j+1 for j in range(3)] for i in range(3)]
flat = [x for row in matrix for x in row]
coords = [(x, y) for x in range(3) for y in range(3)]

Sorting

sorted([3, 1, 2])                    # [1, 2, 3]
sorted([3, 1, 2], reverse=True)      # [3, 2, 1]
sorted(words, key=len)               # sort by length
sorted(words, key=str.lower)         # case-insensitive sort
sorted(dicts, key=lambda x: x['age'])  # sort dicts by key

Dictionary Operations

d = {"a": 1, "b": 2, "c": 3}
d.get("d", 0)           # 0 (default if key missing)
d.keys()                # dict_keys(['a', 'b', 'c'])
d.values()              # dict_values([1, 2, 3])
d.items()               # dict_items([('a', 1), ...])
d.update({"d": 4})      # add/update
d.pop("a")              # remove and return
d.popitem()             # remove last item
d.setdefault("e", 5)    # set if missing
d.clear()               # remove all

Dict Comprehensions

square_dict = {x: x**2 for x in range(5)}
filtered = {k: v for k, v in d.items() if v > 1}
inverted = {v: k for k, v in d.items()}

Counter & defaultdict

from collections import Counter, defaultdict

# Counter
counts = Counter(["a", "b", "a", "c"])  # {'a': 2, 'b': 1, 'c': 1}
counts.most_common(2)  # [('a', 2), ('b', 1)]

# defaultdict
dd = defaultdict(list)
dd["key"].append("value")  # No KeyError
dd["key"]  # ['value']

dd = defaultdict(int)
dd["count"] += 1  # No KeyError

Set Operations

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

a | b          # Union: {1, 2, 3, 4, 5, 6}
a & b          # Intersection: {3, 4}
a - b          # Difference: {1, 2}
a ^ b          # Symmetric diff: {1, 2, 5, 6}
a.issubset(b)  # Subset check
a.issuperset(b)  # Superset check

Control Flow

# if/elif/else
if x > 0:
    print("positive")
elif x < 0:
    print("negative")
else:
    print("zero")

# Ternary operator
status = "adult" if age >= 18 else "minor"

# for loop
for i in range(10):           # 0 to 9
for i in range(2, 10, 2):     # 2, 4, 6, 8
for item in iterable:
for i, item in enumerate(iterable):
for a, b in zip(list1, list2):
for key, value in dict.items():
for item in reversed(list):
for item in sorted(list):

# while loop
while condition:
    break      # exit loop
    continue   # skip to next iteration
    pass       # do nothing

Match-Case (Python 3.10+)

def handle_command(command):
    match command.split():
        case ["quit"]:
            return "Goodbye!"
        case ["hello", name]:
            return f"Hello, {name}!"
        case ["add", *numbers]:
            return sum(int(n) for n in numbers)
        case _:
            return "Unknown command"

Functions

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

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

# *args and **kwargs
def func(*args, **kwargs):
    # args is a tuple
    # kwargs is a dict
    pass

# Lambda
square = lambda x: x ** 2
add = lambda a, b: a + b

# Decorator
import functools
def my_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

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

# Higher-order functions
map(str, [1, 2, 3])           # ['1', '2', '3']
filter(lambda x: x > 0, [-1, 1, -2, 2])  # [1, 2]
functools.reduce(lambda a, b: a + b, [1, 2, 3])  # 6
sorted(words, key=str.lower)

Common Imports

import os                    # Operating system interface
import sys                   # System parameters
import json                  # JSON encoding/decoding
import re                    # Regular expressions
import math                  # Math functions
import random                # Random numbers
import datetime              # Date and time
import logging               # Logging
import unittest              # Testing
from pathlib import Path     # File paths
from typing import Optional, List, Dict, Union  # Type hints
from collections import Counter, defaultdict, namedtuple
from functools import lru_cache, partial, reduce
from itertools import chain, groupby, islice, product, permutations
from contextlib import contextmanager, suppress, redirect_stdout

File I/O

# Read entire file
with open("file.txt") as f:
    data = f.read()

# Read lines
with open("file.txt") as f:
    lines = f.readlines()  # List of lines
    for line in f:          # Memory-efficient
        process(line)

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

# Append
with open("file.txt", "a") as f:
    f.write("more content")

# Read/Write binary
with open("file.bin", "rb") as f:
    data = f.read()

pathlib (Recommended)

from pathlib import Path

# Create paths
p = Path("dir/file.txt")
p = Path.home() / "Documents" / "file.txt"

# Read/write
p.write_text("hello")
content = p.read_text()

# Path operations
p.exists()
p.is_file()
p.is_dir()
p.name          # "file.txt"
p.stem          # "file"
p.suffix        # ".txt"
p.parent        # Path("dir")

# Glob
list(Path(".").glob("*.py"))
list(Path(".").rglob("*.py"))  # Recursive

# Create directories
Path("dir/subdir").mkdir(parents=True, exist_ok=True)

Error Handling

try:
    risky_operation()
except ValueError as e:
    print(f"Value error: {e}")
except (TypeError, KeyError) as e:
    print(f"Type/Key error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
    raise  # Re-raise the exception
else:
    print("Success!")  # Runs if no exception
finally:
    cleanup()  # Always runs

# Raise exceptions
raise ValueError("Invalid value")
raise TypeError("Wrong type")

# Custom exceptions
class AppError(Exception):
    def __init__(self, message, code=None):
        super().__init__(message)
        self.code = code

Context Managers

from contextlib import contextmanager

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

with timer():
    slow_operation()

# Suppress exceptions
from contextlib import suppress
with suppress(FileNotFoundError):
    os.remove("nonexistent.txt")

Virtual Environment

# Create
python -m venv venv

# Activate (Linux/Mac)
source venv/bin/activate

# Activate (Windows)
venv\Scripts\activate

# Install packages
pip install -r requirements.txt

# Save dependencies
pip freeze > requirements.txt

# Deactivate
deactivate

Common Patterns

# Swap variables
a, b = b, a

# Unpack list
first, *middle, last = [1, 2, 3, 4, 5]

# Check membership
if item in collection:
    pass

# Chained comparison
if 0 < x < 100:
    pass

# Walrus operator (Python 3.8+)
if (n := len(data)) > 10:
    print(f"Too long: {n}")

# Dictionary merge (Python 3.9+)
merged = dict1 | dict2

# Exception groups (Python 3.11+)
try:
    ...
except* ValueError as eg:
    for e in eg.exceptions:
        ...
except* TypeError as eg:
    ...

One-Liners

# Flatten list
flat = [x for row in matrix for x in row]

# Filter and map
result = list(map(str, filter(lambda x: x > 0, numbers)))

# Dictionary from two lists
d = dict(zip(keys, values))

# Count occurrences
counts = Counter(words)

# Group by
from itertools import groupby
sorted_data = sorted(data, key=lambda x: x['category'])
for key, group in groupby(sorted_data, key=lambda x: x['category']):
    print(key, list(group))

# Chunk list
def chunks(lst, n):
    for i in range(0, len(lst), n):
        yield lst[i:i + n]

Standard Library Highlights

# os — File system operations
os.listdir(".")
os.makedirs("dir/subdir", exist_ok=True)
os.environ.get("HOME")
os.path.join("dir", "file.txt")

# sys — System info
sys.argv           # Command-line arguments
sys.exit(0)        # Exit with code
sys.path           # Module search path

# json — JSON handling
json.dumps({"a": 1})  # Serialize
json.loads('{"a": 1}')  # Deserialize
json.dump(data, open("file.json", "w"))
data = json.load(open("file.json"))

# datetime — Date and time
from datetime import datetime, timedelta
now = datetime.now()
yesterday = now - timedelta(days=1)
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
parsed = datetime.strptime("2024-01-15", "%Y-%m-%d")

# random — Random numbers
import random
random.randint(1, 10)  # Random int in range
random.choice([1, 2, 3])  # Random element
random.shuffle(lst)  # Shuffle in-place
random.sample(lst, 3)  # 3 unique random elements

# math — Math functions
import math
math.ceil(3.2)    # 4
math.floor(3.8)   # 3
math.sqrt(16)     # 4.0
math.factorial(5)  # 120
math.gcd(12, 8)   # 4

# itertools — Iterators
import itertools
itertools.chain([1, 2], [3, 4])  # 1, 2, 3, 4
itertools.product([1, 2], [3, 4])  # (1,3), (1,4), (2,3), (2,4)
itertools.permutations([1, 2, 3])  # All permutations
itertools.combinations([1, 2, 3], 2)  # 2-combinations

Key Takeaways

  1. Keep this cheatsheet handy for quick reference
  2. Practice patterns until they become second nature
  3. Read Python source code to learn idioms
  4. Use help() and dir() for interactive help
  5. The Python docs are excellent — use them!
  6. Use type hints for better code clarity
  7. Prefer pathlib over os.path for file operations
  8. Use f-strings for string formatting
  9. Use itertools for efficient iteration
  10. Write Pythonic code — follow PEP 8

Premium Content

Python Cheatsheet — Quick Reference Guide

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
💼Interview Prep
📜Certificates
🤝Community Access

Already a member? Log in

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement