Reference Programming cheat sheets Rev 2026.11

Reference sheets

Programming cheat sheets

The syntax I keep looking up, for Python, JavaScript, Java, C++ and SQL. Every entry is copy-paste ready and says when to reach for it.

Python

Readable, batteries included, and the default for scripting and AI work.

Basic Syntax

Variables & Types

# Variables (dynamic typing)
name = "John"          # string
age = 25              # int
height = 5.9          # float
is_student = True     # boolean
items = [1, 2, 3]     # list
coords = (10, 20)     # tuple
person = {"name": "John"}  # dict

When to use: Store and manipulate different types of data. Python automatically infers types.

Control Flow

# If statements
if age >= 18:
    print("Adult")
elif age >= 13:
    print("Teen")
else:
    print("Child")

# Loops
for i in range(5):
    print(i)

for item in items:
    print(item)

while condition:
    # do something
    break

When to use: Control program execution flow with conditions and loops.

Operators

# Arithmetic
+ - * / // % **

# Comparison  
== != < > <= >= 

# Logical
and or not

# Membership
in, not in

# Identity
is, is not

When to use: Perform operations on variables and test conditions.

Functions

Function Definition

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

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

# Function with *args and **kwargs
def flexible_func(*args, **kwargs):
    print(f"Args: {args}")
    print(f"Kwargs: {kwargs}")

# Decorators
def timer(func):
    def wrapper(*args, **kwargs):
        # timing logic
        return func(*args, **kwargs)
    return wrapper

@timer
def my_function():
    pass

When to use: Organize code into reusable blocks. Use decorators for cross-cutting concerns.

Data Structures

Lists

# Creation and operations
numbers = [1, 2, 3, 4, 5]
numbers.append(6)        # Add to end
numbers.insert(0, 0)     # Insert at index
numbers.remove(3)        # Remove value
popped = numbers.pop()   # Remove and return last
numbers.extend([7, 8])   # Add multiple items

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

When to use: Store ordered, mutable collections. Use for sequences that need frequent modification.

Dictionaries

# Creation and operations
person = {"name": "John", "age": 30}
person["city"] = "NYC"         # Add key-value
age = person.get("age", 0)     # Safe access
person.update({"job": "Dev"})  # Add multiple

# Dictionary comprehension
squares = {x: x**2 for x in range(5)}

# Useful methods
keys = person.keys()
values = person.values()
items = person.items()

When to use: Store key-value pairs for fast lookups. Use when you need to associate data.

Sets

# Creation and operations
unique_nums = {1, 2, 3, 4, 5}
unique_nums.add(6)
unique_nums.remove(1)
unique_nums.discard(10)  # Won't error if not found

# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2         # {1, 2, 3, 4, 5}
intersection = set1 & set2  # {3}
difference = set1 - set2    # {1, 2}

When to use: Store unique values and perform mathematical set operations efficiently.

Collections Module

from collections import defaultdict, Counter, deque

# defaultdict - never raises KeyError
dd = defaultdict(list)
dd['key'].append('value')

# Counter - count hashable objects
counter = Counter(['a', 'b', 'a', 'c', 'b'])
# Counter({'a': 2, 'b': 2, 'c': 1})

# deque - double-ended queue
dq = deque([1, 2, 3])
dq.appendleft(0)  # Add to left
dq.append(4)      # Add to right

When to use: Specialized data structures for specific use cases like counting, queues, and default values.

Input/Output

Console I/O

# Output
print("Hello, World!")
print(f"Name: {name}, Age: {age}")
print("Values:", 1, 2, 3, sep=", ", end="\n")

# Input
name = input("Enter your name: ")
age = int(input("Enter your age: "))

# Formatted output
print(f"Pi is approximately {3.14159:.2f}")
print("Score: {:>10}".format(score))

When to use: Interact with users through console input/output and format displayed data.

File I/O

Reading Files

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

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

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

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

When to use: Read data from files. Use context managers (with) for automatic file closing.

Writing Files

# Write to file
with open('output.txt', 'w') as f:
    f.write("Hello, World!\n")
    f.writelines(["Line 1\n", "Line 2\n"])

# Append to file
with open('log.txt', 'a') as f:
    f.write("New log entry\n")

# Write JSON
import json
data = {"name": "John", "age": 30}
with open('data.json', 'w') as f:
    json.dump(data, f, indent=2)

When to use: Save data to files. Use different modes: "w" (write), "a" (append), "r+" (read/write).

Random Numbers

Random Module

import random

# Random float between 0 and 1
rand_float = random.random()

# Random integer in range
rand_int = random.randint(1, 10)  # 1 to 10 inclusive
rand_range = random.randrange(0, 10, 2)  # 0,2,4,6,8

# Random choice from sequence
color = random.choice(['red', 'blue', 'green'])
colors = random.choices(['r', 'g', 'b'], k=5)  # With replacement
sample = random.sample([1,2,3,4,5], 3)  # Without replacement

# Shuffle list in place
random.shuffle(my_list)

# Set seed for reproducibility
random.seed(42)

When to use: Generate random numbers for simulations, games, sampling, and testing.

Error Handling

Try/Except

# Basic exception handling
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError as e:
    print(f"Value error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
else:
    print("No errors occurred")
finally:
    print("This always runs")

# Raising exceptions
if age < 0:
    raise ValueError("Age cannot be negative")

When to use: Handle errors gracefully and provide meaningful error messages to users.

Time complexity
  • O(1) · constant time
  • O(log n) · logarithmic
  • O(n) · linear time
  • O(n²) · quadratic time
Data structures
  • Arrays · fast indexed access
  • Hash tables · O(1) lookups
  • Trees · hierarchical data
  • Graphs · network relationships
Best practices
  • Write clear, readable code
  • Handle errors gracefully
  • Use meaningful names
  • Comment complex logic