Python Quick Reference Cheatsheet
Python Syntax, Built-Ins, and Common Patterns
Category: Programming
Level: Beginner — Intermediate
Python quick reference covering data types, strings, lists, dictionaries, functions, classes, file I/O, error handling, comprehensions, and essential libraries.
📦 Data Types
# Integers
x = 42
x = 1_000_000 # Underscores for readability
# Floats
pi = 3.14159
sci = 1.5e-3 # Scientific notation = 0.0015
# Strings
name = "Alice"
name = 'Alice'
multiline = """Line one
Line two"""
# Booleans
is_valid = True
is_empty = False
# None
result = None
# Type checking
type(x) #
isinstance(x, int) # True
# Type conversion
int("42") # 42
float("3.14") # 3.14
str(100) # "100"
bool(0) # False
bool(1) # True
🔤 Strings
s = "Hello, World!"
# Length
len(s) # 13
# Access & slicing
s[0] # "H"
s[-1] # "!"
s[0:5] # "Hello"
s[7:] # "World!"
s[::-1] # "!dlroW ,olleH" (reversed)
# Case methods
s.upper() # "HELLO, WORLD!"
s.lower() # "hello, world!"
s.title() # "Hello, World!"
s.capitalize() # "Hello, world!"
s.swapcase() # "hELLO, wORLD!"
# Search & check
s.find("World") # 7 (index) or -1 if not found
s.count("l") # 3
s.startswith("Hello") # True
s.endswith("!") # True
"World" in s # True
# Modify
s.strip() # Remove leading/trailing whitespace
s.lstrip() # Remove left whitespace
s.rstrip() # Remove right whitespace
s.replace("World", "Python") # "Hello, Python!"
s.split(", ") # ["Hello", "World!"]
", ".join(["a", "b", "c"]) # "a, b, c"
# Formatting
name = "Alice"
age = 30
# f-strings (recommended)
f"Name: {name}, Age: {age}"
f"Pi is approximately {3.14159:.2f}"
f"{age:>10}" # Right-align in 10 chars
# format() method
"Name: {}, Age: {}".format(name, age)
"Name: {name}".format(name=name)
# Checking content
s.isdigit() # All chars are digits?
s.isalpha() # All chars are letters?
s.isalnum() # All chars are alphanumeric?
s.isspace() # All chars are whitespace?
📋 Lists
fruits = ["apple", "banana", "cherry"]
# Access
fruits[0] # "apple"
fruits[-1] # "cherry"
fruits[1:3] # ["banana", "cherry"]
# Modify
fruits.append("date") # Add to end
fruits.insert(1, "avocado") # Insert at index
fruits.extend(["elderberry", "fig"]) # Add multiple
fruits.remove("banana") # Remove by value (first match)
fruits.pop() # Remove and return last item
fruits.pop(0) # Remove and return at index
del fruits[0] # Delete at index
# Search
"apple" in fruits # True
fruits.index("cherry") # Returns index
fruits.count("apple") # Count occurrences
# Sorting
fruits.sort() # Sort in place (ascending)
fruits.sort(reverse=True) # Sort in place (descending)
sorted(fruits) # Returns new sorted list
fruits.reverse() # Reverse in place
# Info
len(fruits) # Length
min(fruits) # Smallest
max(fruits) # Largest
sum([1, 2, 3]) # Sum (numbers only)
# Copying (avoid reference issues)
copy = fruits.copy() # Shallow copy
copy = fruits[:] # Shallow copy (slicing)
# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
flat = [item for sublist in nested for item in sublist]
📖 Dictionaries
person = {"name": "Alice", "age": 30, "city": "Phoenix"}
# Access
person["name"] # "Alice"
person.get("age") # 30
person.get("email", "N/A") # "N/A" (default if missing)
# Modify
person["email"] = "alice@example.com" # Add or update
person.update({"age": 31, "job": "Developer"})
# Delete
del person["city"]
person.pop("email") # Remove and return value
person.pop("missing", None) # Safe pop with default
# Check
"name" in person # True (checks keys)
"Alice" in person.values() # True
# Iterate
for key in person: # Keys
for key in person.keys(): # Keys (explicit)
for value in person.values(): # Values
for key, value in person.items(): # Key-value pairs
# Info
len(person) # Number of keys
# Useful methods
person.keys() # dict_keys(['name', 'age'...])
person.values() # dict_values(['Alice', 30...])
person.items() # dict_items([('name','Alice')...])
person.setdefault("score", 0) # Set only if key doesn't exist
# Dict comprehension
squares = {x: x**2 for x in range(5)}
filtered = {k: v for k, v in person.items() if v is not None}
# Merge dicts (Python 3.9+)
merged = dict1 | dict2
dict1 |= dict2 # Update in place
🎯 Sets & Tuples
# --- SETS (unique, unordered) ---
s = {1, 2, 3, 4}
s = set([1, 2, 2, 3]) # {1, 2, 3} — duplicates removed
s.add(5)
s.remove(3) # Raises KeyError if missing
s.discard(99) # Safe remove (no error)
# Set operations
a = {1, 2, 3}
b = {2, 3, 4}
a | b # Union: {1, 2, 3, 4}
a & b # Intersection: {2, 3}
a - b # Difference: {1}
a ^ b # Symmetric difference: {1, 4}
2 in a # True
# --- TUPLES (ordered, immutable) ---
t = (1, 2, 3)
t = 1, 2, 3 # Parentheses optional
single = (42,) # Single-element tuple needs comma
# Access like lists
t[0] # 1
t[-1] # 3
t[1:3] # (2, 3)
# Useful
len(t)
x, y, z = t # Unpacking
x, *rest = t # Extended unpacking
⚙️ Functions
# Basic function
def greet(name):
return f"Hello, {name}!"
# Default arguments
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# *args — variable positional arguments
def add(*numbers):
return sum(numbers)
add(1, 2, 3) # 6
# **kwargs — variable keyword arguments
def display(**info):
for key, value in info.items():
print(f"{key}: {value}")
display(name="Alice", age=30)
# Combined
def func(pos_arg, *args, keyword="default", **kwargs):
pass
# Type hints (Python 3.5+)
def add(a: int, b: int) -> int:
return a + b
# Lambda — anonymous single-expression function
square = lambda x: x ** 2
sorted_list = sorted(items, key=lambda x: x["age"])
# Docstrings
def calculate(x, y):
"""
Calculate the sum of x and y.
Args:
x: First number
y: Second number
Returns:
Sum of x and y
"""
return x + y
🏗️ Classes & OOP
class Animal:
# Class variable (shared across instances)
kingdom = "Animalia"
def __init__(self, name, sound):
# Instance variables
self.name = name
self.sound = sound
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}')"
@classmethod
def from_dict(cls, data):
return cls(data["name"], data["sound"])
@staticmethod
def is_animal(obj):
return isinstance(obj, Animal)
# Inheritance
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, "Woof")
self.breed = breed
def speak(self): # Override parent method
return f"{self.name} barks!"
# Usage
dog = Dog("Rex", "Labrador")
dog.speak() # "Rex barks!"
dog.kingdom # "Animalia"
isinstance(dog, Animal) # True
# 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 cannot be negative")
self._radius = value
@property
def area(self):
import math
return math.pi * self._radius ** 2
🔄 Control Flow
# if / elif / else
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
# Ternary (one-line conditional)
result = "pass" if score >= 70 else "fail"
# for loop
for i in range(5): # 0, 1, 2, 3, 4
for i in range(2, 10, 2): # 2, 4, 6, 8
for item in my_list: # iterate list
for i, item in enumerate(my_list): # with index
for key, val in my_dict.items(): # iterate dict
# Loop control
break # Exit loop
continue # Skip to next iteration
else: # Runs if loop didn't break
# while loop
count = 0
while count < 5:
count += 1
# Useful built-ins in loops
zip([1,2,3], ["a","b","c"]) # [(1,"a"), (2,"b"), (3,"c")]
reversed(my_list)
sorted(my_list, key=lambda x: x["name"])
filter(lambda x: x > 0, numbers)
map(lambda x: x * 2, numbers)
🛡️ Error Handling
# Basic try/except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
# Multiple exception types
try:
value = int(input("Enter a number: "))
except ValueError:
print("Not a valid number")
except (TypeError, AttributeError):
print("Type error occurred")
except Exception as e:
print(f"Unexpected error: {e}")
else:
print("No exception occurred") # Runs if no exception
finally:
print("Always runs") # Cleanup goes here
# Raise exceptions
raise ValueError("Invalid input")
raise ValueError(f"Expected positive number, got {x}")
# Custom exceptions
class AppError(Exception):
def __init__(self, message, code=None):
super().__init__(message)
self.code = code
# Context managers
with open("file.txt", "r") as f:
content = f.read()
# File automatically closed after block
📂 File I/O
# Read entire file
with open("file.txt", "r") as f:
content = f.read()
# Read line by line (memory efficient for large files)
with open("file.txt", "r") as f:
for line in f:
print(line.strip())
# Read all lines into a list
with open("file.txt", "r") as f:
lines = f.readlines()
# Write (overwrites existing)
with open("output.txt", "w") as f:
f.write("Hello\n")
f.writelines(["Line 1\n", "Line 2\n"])
# Append
with open("log.txt", "a") as f:
f.write("New log entry\n")
# File modes
"r" # Read (default)
"w" # Write (creates or overwrites)
"a" # Append
"rb" # Read binary
"wb" # Write binary
# JSON files
import json
with open("data.json", "r") as f:
data = json.load(f)
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# JSON string conversion
json_string = json.dumps({"key": "value"})
data = json.loads(json_string)
# CSV files
import csv
with open("data.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["column_name"])
with open("output.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "age"])
writer.writeheader()
writer.writerows([{"name": "Alice", "age": 30}])
🛠️ Essential Built-in Functions
# Type & info
type(obj) # Get type
id(obj) # Memory address
dir(obj) # List attributes/methods
help(obj) # Documentation
vars(obj) # Object's __dict__
# Math
abs(-5) # 5
round(3.14159, 2) # 3.14
pow(2, 10) # 1024
divmod(17, 5) # (3, 2) — quotient and remainder
min(1, 2, 3) # 1
max(1, 2, 3) # 3
sum([1, 2, 3]) # 6
# Sequences
len(obj) # Length
range(start, stop, step)
enumerate(iterable) # (index, value) pairs
zip(*iterables) # Pair up iterables
reversed(sequence) # Reverse iterator
sorted(iterable, key=None, reverse=False)
# Functional
map(func, iterable) # Apply func to each item
filter(func, iterable) # Keep items where func is True
any(iterable) # True if any item is truthy
all(iterable) # True if all items are truthy
# I/O
print(*objects, sep=" ", end="\n")
input("Prompt: ") # Always returns string
📦 Common Standard Library Modules
# os — operating system interface
import os
os.getcwd() # Current directory
os.listdir(".") # List directory contents
os.path.exists("file.txt")
os.path.join("dir", "file.txt")
os.makedirs("dir/subdir", exist_ok=True)
os.environ.get("HOME") # Environment variable
# sys — system-specific parameters
import sys
sys.argv # Command-line arguments
sys.exit(0) # Exit program
sys.path # Module search paths
# datetime
from datetime import datetime, timedelta
now = datetime.now()
now.strftime("%Y-%m-%d %H:%M:%S")
datetime.strptime("2026-01-15", "%Y-%m-%d")
future = now + timedelta(days=30)
# pathlib — modern file paths
from pathlib import Path
p = Path("dir/file.txt")
p.exists()
p.read_text()
p.write_text("content")
p.stem # Filename without extension
p.suffix # File extension
p.parent # Parent directory
list(Path(".").glob("*.py"))
# re — regular expressions
import re
re.search(r"\d+", text) # Find first match
re.findall(r"\d+", text) # Find all matches
re.sub(r"\s+", " ", text) # Replace pattern
re.match(r"^Hello", text) # Match at start
# collections
from collections import Counter, defaultdict, deque, namedtuple
Counter("hello") # {'l': 2, 'h': 1...}
defaultdict(list) # Default value factory
deque([1,2,3], maxlen=5) # Efficient queue
# random
import random
random.random() # Float 0.0 to 1.0
random.randint(1, 10) # Integer 1 to 10
random.choice(my_list) # Random element
random.shuffle(my_list) # Shuffle in place
random.sample(my_list, 3) # 3 unique random items
→ Related: Python for Beginners Blog Post | Python for Security Automation Tutorial | Programming Learning Path
📬 New Cheatsheets Added Regularly
New quick-reference guides are added as the hub grows. Subscribe to the newsletter to know when new ones drop.
→ Subscribe to the Newsletter