Python Cheat Sheet: Complete Quick Reference Guide for Developers

Whether you’re just starting with Python or need a quick syntax refresher, this comprehensive cheat sheet has you covered. I’ve compiled the most commonly used Python patterns, built-in functions, and standard library essentials into one reference guide.

This isn’t a tutorial—it’s a quick reference designed for speed. Bookmark this page and come back whenever you need to remember the syntax for list comprehensions, decorator patterns, or how to properly use context managers.

Data Types

# Numbers
x = 5              # int
y = 3.14           # float
z = 1 + 2j         # complex

# Strings
s = "Hello"
s = 'Hello'
s = """Multi
line"""

# Boolean
b = True
b = False

# None
n = None

# Type checking
type(x)           # <class 'int'>
isinstance(x, int) # True

String Operations

# Concatenation
s = "Hello" + " " + "World"

# Formatting
name = "Alice"
age = 30
s = f"Name: {name}, Age: {age}"         # f-string (preferred)
s = "Name: {}, Age: {}".format(name, age)
s = "Name: %s, Age: %d" % (name, age)

# Common methods
s.upper()          # "HELLO"
s.lower()          # "hello"
s.strip()          # Remove whitespace
s.split()          # Split into list
s.replace('H', 'J')# Replace
s.startswith('H')  # True/False
s.endswith('o')    # True/False
s.find('e')        # Index or -1
s.count('l')       # Count occurrences

# Slicing
s[0]              # First character
s[-1]             # Last character
s[1:4]            # Substring
s[:3]             # First 3
s[3:]             # From 3 to end
s[::2]            # Every 2nd character
s[::-1]           # Reverse

Lists

# Creation
lst = [1, 2, 3, 4, 5]
lst = list(range(5))

# Access
lst[0]            # First element
lst[-1]           # Last element
lst[1:3]          # Slicing

# Modification
lst.append(6)     # Add to end
lst.insert(0, 0)  # Insert at index
lst.extend([7,8]) # Add multiple
lst.remove(3)     # Remove first 3
lst.pop()         # Remove & return last
lst.pop(0)        # Remove & return at index
del lst[0]        # Delete at index

# Operations
len(lst)          # Length
max(lst)          # Maximum
min(lst)          # Minimum
sum(lst)          # Sum
lst.sort()        # Sort in place
sorted(lst)       # Return sorted copy
lst.reverse()     # Reverse in place
reversed(lst)     # Return reversed iterator
lst.count(2)      # Count occurrences
lst.index(3)      # Find index

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

Dictionaries

# Creation
d = {'name': 'Alice', 'age': 30}
d = dict(name='Alice', age=30)

# Access
d['name']         # Get value
d.get('name')     # Get or None
d.get('key', 'default')  # Get or default

# Modification
d['city'] = 'NYC' # Add/update
del d['age']      # Delete
d.pop('age')      # Remove & return

# Operations
len(d)            # Number of keys
'name' in d       # Check key exists
d.keys()          # Keys view
d.values()        # Values view
d.items()         # (key, value) pairs

# Iteration
for key in d:
    print(key, d[key])

for key, value in d.items():
    print(key, value)

# Dict comprehension
{x: x**2 for x in range(5)}

Sets

# Creation
s = {1, 2, 3}
s = set([1, 2, 3])

# Operations
s.add(4)          # Add element
s.remove(2)       # Remove (error if missing)
s.discard(2)      # Remove (no error)
s.pop()           # Remove arbitrary

# Set operations
a = {1, 2, 3}
b = {3, 4, 5}
a | b             # Union {1,2,3,4,5}
a & b             # Intersection {3}
a - b             # Difference {1,2}
a ^ b             # Symmetric difference {1,2,4,5}

# Tests
3 in s            # Membership
a.issubset(b)     # Subset test
a.issuperset(b)   # Superset test

Tuples

# Creation (immutable)
t = (1, 2, 3)
t = 1, 2, 3       # Parentheses optional

# Access
t[0]              # First element
t[-1]             # Last element

# Unpacking
x, y, z = t
x, *rest = t      # x=1, rest=[2,3]

Control Flow

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

# Ternary operator
result = "even" if x % 2 == 0 else "odd"

# For loop
for i in range(10):
    print(i)

for item in lst:
    print(item)

for i, item in enumerate(lst):
    print(i, item)

# While loop
while x > 0:
    x -= 1

# Break and continue
for i in range(10):
    if i == 5:
        break     # Exit loop
    if i % 2 == 0:
        continue  # Skip to next iteration

Functions

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

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

# Variable arguments
def sum_all(*args):
    return sum(args)

# Keyword arguments
def person(**kwargs):
    return kwargs

# Type hints
def add(x: int, y: int) -> int:
    return x + y

# Lambda function
square = lambda x: x**2

Classes

# Basic class
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, I'm {self.name}"

# Usage
p = Person("Alice", 30)
print(p.name)
print(p.greet())

# Inheritance
class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade

# Properties
class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError("Radius must be positive")
        self._radius = value

    @property
    def area(self):
        return 3.14 * self._radius ** 2

Error Handling

# Try/except
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
except Exception as e:
    print(f"Error: {e}")
else:
    print("No errors")
finally:
    print("Always runs")

# Raising exceptions
raise ValueError("Invalid value")

# Custom exception
class CustomError(Exception):
    pass

raise CustomError("Something went wrong")

File I/O

# Read file
with open('file.txt', 'r') as f:
    content = f.read()

# Read lines
with open('file.txt', 'r') as f:
    lines = f.readlines()

# Iterate lines
with open('file.txt', 'r') as f:
    for line in f:
        print(line.strip())

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

# Append
with open('file.txt', 'a') as f:
    f.write("World\n")

# JSON
import json

# Write JSON
with open('data.json', 'w') as f:
    json.dump(data, f, indent=2)

# Read JSON
with open('data.json', 'r') as f:
    data = json.load(f)

Common Built-in Functions

# Type conversion
int("123")        # String to int
float("3.14")     # String to float
str(123)          # Int to string
list("abc")       # String to list
tuple([1,2,3])    # List to tuple
set([1,2,2,3])    # List to set

# Math
abs(-5)           # Absolute value
round(3.7)        # Round
pow(2, 3)         # Power (2^3)
max(1, 2, 3)      # Maximum
min(1, 2, 3)      # Minimum
sum([1, 2, 3])    # Sum

# Iteration
len(lst)          # Length
all([True, True]) # All true
any([False, True])# Any true
enumerate(lst)    # (index, value)
zip(lst1, lst2)   # Combine lists
reversed(lst)     # Reverse iterator
sorted(lst)       # Sorted list

# Functional
map(func, lst)    # Apply function
filter(func, lst) # Filter elements

Comprehensions

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

# Dict comprehension
{x: x**2 for x in range(5)}

# Set comprehension
{x**2 for x in range(10)}

# Generator expression
(x**2 for x in range(10))

Common Standard Library

# os - Operating system
import os
os.getcwd()           # Current directory
os.listdir('.')       # List files
os.mkdir('dir')       # Create directory
os.path.exists('file')# Check exists
os.path.join('a', 'b')# Join paths

# sys - System
import sys
sys.argv              # Command line args
sys.exit()            # Exit program

# datetime
from datetime import datetime, timedelta
now = datetime.now()
date = datetime(2024, 1, 1)
tomorrow = now + timedelta(days=1)
now.strftime('%Y-%m-%d')  # Format

# random
import random
random.random()       # 0.0 to 1.0
random.randint(1, 10) # 1 to 10
random.choice(lst)    # Random element
random.shuffle(lst)   # Shuffle in place

# collections
from collections import defaultdict, Counter, deque
counts = Counter(['a', 'b', 'a'])
d = defaultdict(list)
queue = deque([1, 2, 3])

# itertools
from itertools import chain, combinations, product
chain([1,2], [3,4])   # [1,2,3,4]
combinations([1,2,3], 2)  # [(1,2), (1,3), (2,3)]
product([1,2], [3,4]) # [(1,3), (1,4), (2,3), (2,4)]

# functools
from functools import lru_cache, reduce
@lru_cache(maxsize=None)
def fibonacci(n):
    return n if n < 2 else fibonacci(n-1) + fibonacci(n-2)

reduce(lambda x, y: x+y, [1,2,3,4])  # 10

# re - Regular expressions
import re
re.search(r'\d+', 'abc123')
re.findall(r'\w+', text)
re.sub(r'\d+', 'X', text)

Virtual Environment

# Create virtual environment
python -m venv .venv

# Activate (Unix/macOS)
source .venv/bin/activate

# Activate (Windows)
.venv\Scripts\activate

# Deactivate
deactivate

# Install packages
pip install requests

# Save dependencies
pip freeze > requirements.txt

# Install from requirements
pip install -r requirements.txt

Modern Python (3.10+)

# Match statement (3.10+)
match status:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case _:
        print("Other")

# Union types (3.10+)
def process(value: int | str) -> int | None:
    pass

# Structural pattern matching
match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print(f"Y-axis at {y}")
    case (x, 0):
        print(f"X-axis at {x}")
    case (x, y):
        print(f"Point at {x}, {y}")

Common Patterns

# Swap variables
a, b = b, a

# Multiple assignment
x = y = z = 0

# Conditional expression
result = x if condition else y

# Check multiple values
if x in [1, 2, 3]:
    pass

# Get with default
value = d.get('key', 'default')

# Enumerate with start
for i, item in enumerate(lst, start=1):
    print(f"{i}. {item}")

# Chaining comparisons
if 0 < x < 10:
    pass

# Any/all
if any(x > 5 for x in lst):
    pass

if all(x > 0 for x in lst):
    pass

Decorators

# Basic decorator
def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end-start:.2f}s")
        return result
    return wrapper

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

# Decorator with arguments
def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def greet(name):
    print(f"Hello {name}")

Context Managers

# Using with statement
with open('file.txt') as f:
    content = f.read()

# Custom context manager
class Timer:
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        self.end = time.time()
        print(f"Elapsed: {self.end - self.start:.2f}s")

with Timer():
    # Code to time
    pass

Next Steps

This cheat sheet covers the essential Python syntax and patterns you’ll use daily. To continue your Python journey:

  • Set up a proper development environment with virtual environments and modern tooling
  • Learn testing with pytest to write reliable code
  • Explore frameworks like FastAPI for web development or pandas for data analysis
  • Practice regularly by solving coding challenges on platforms like LeetCode or HackerRank

Keep this reference bookmarked—even experienced developers look up syntax regularly. The key is knowing what’s possible and where to find the details when you need them.

External Resources

Comments

Kevin Duane

Kevin Duane

Cloud architect and developer sharing practical solutions.