Python Cheat Sheet
Every built-in, syntax pattern, and idiom. Searchable, filterable by level, copy-ready.
Every built-in, syntax pattern, and idiom. Searchable, filterable by level, copy-ready.
You already know that syntax errors and forgotten method names waste time. A good Python cheat sheet fixes that fast.
Python is flexible, readable, and used everywhere from data science to web development. But even experienced developers blank on slicing syntax or can't remember if it's .append() or .add().
This guide covers the core reference points you actually reach for:
Data types and variable syntax
Built-in functions and string methods
Loops, conditionals, and list comprehension
File handling, error handling, and OOP basics
Quick-reference snippets for Python 3
No fluff. Just the Python quick reference you need to write cleaner scripts faster.
Python is a high-level, interpreted programming language built around readability and clean syntax.
Guido van Rossum created it in 1991. The Python Software Foundation maintains it today.
Python 3 is the current standard. Python 2 hit end-of-life in 2020, so unless you're maintaining legacy code, there's no reason to touch it.
It covers scripting, automation, data science (NumPy, Pandas), web development (Django, Flask), and machine learning. The Python Package Index (PyPI) holds over 450,000 packages, all installable via pip.
Python uses indentation instead of braces to define code blocks. The interpreter enforces this. Get it wrong and the script fails immediately.
No type declarations needed. Variables are assigned directly and can hold any data type.
Core built-in types:
int, float - whole numbers and decimals
str - text strings
bool - True or False
list, tuple, dict, set - collection types
Type conversion uses built-in functions: int(), str(), float(), list(). No imports needed.
Single-line comments use #. Multi-line comments use triple quotes (''' or """), though technically those are string literals, not real comments.
# Single-line comment
'''
This spans
multiple lines
'''
PEP 8 recommends keeping comments short and updated when code changes.
Four spaces per level is the PEP 8 standard. Tabs work, but mixing tabs and spaces in Python 3 throws a TabError.
Common mistakes: forgetting to indent after a colon, inconsistent spacing, copy-pasting code with mismatched indentation from another editor.
IndentationError and TabError are the two exceptions Python raises when indentation is wrong. Both are easy to spot once you know what you're looking for.
Standard math plus a few Python-specific ones:
|
Operator |
Operation |
Example |
|---|---|---|
|
|
Addition |
|
|
|
Subtraction |
|
|
|
Multiplication |
|
|
|
Division (float) |
|
|
|
Floor division |
|
|
|
Modulus |
|
|
|
Exponent |
|
// and ** are the ones people forget. // floors the result; ** handles powers.
Return True or False. Used in conditionals and loops.
==, !=, >, <, >=, <=
Note: == checks value equality. is checks object identity. They're not the same thing.
and, or, not - combine or invert boolean expressions.
x = 5
print(x > 2 and x < 10) # True
print(not x > 10) # True
= assigns. Shorthand operators modify and reassign in one step:
+=, -=, *=, /=, //=, %=, **=
x = 10
x += 5 # x is now 15
x **= 2 # x is now 225
Work on binary representations of integers. Less common in general scripting, but useful in systems programming and data processing.
& (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift)
String methods don't modify the original. They return a new string.
Common methods:
.upper(), .lower() - change case
.strip() - remove leading/trailing whitespace
.split(separator) - split into a list
.replace(old, new) - swap substrings
.format() - insert values into a template
f-strings - the cleanest way to format strings in Python 3.6+
name = "python"
print(name.upper()) # PYTHON
print(f"Hello, {name}!") # Hello, python!
f-strings are faster and more readable than .format(). Use them by default.
Ordered, mutable, allows duplicates.
Key methods:
.append(item) - add to end
.remove(item) - remove first match
.pop(index) - remove and return item
.sort() - sort in place
.reverse() - reverse in place
fruits = ["apple", "banana", "cherry"]
fruits.append("mango")
fruits.sort()
print(fruits[1:3]) # list slicing
List slicing syntax: list[start:stop:step]. The stop index is exclusive.
Like lists but immutable. Once created, the values can't change.
coords = (10.5, 20.3)
Use tuples for data that shouldn't change: coordinates, RGB values, database records. Slightly faster than lists for iteration.
Key-value pairs. Keys must be unique and immutable.
Core methods:
.get(key) - returns value or None (no KeyError)
.keys(), .values(), .items() - views of the dict
Dict comprehension: {k: v for k, v in iterable}
user = {"name": "Alex", "age": 30}
print(user.get("email", "N/A")) # N/A
.get() is safer than direct key access when the key might not exist.
Unordered, no duplicates. Good for membership testing and removing duplicates from a list.
.add(item), .remove(item)
| union, & intersection, - difference
a = {1, 2, 3}
b = {3, 4, 5}
print(a & b) # {3}
print(a | b) # {1, 2, 3, 4, 5}
Python's conditional syntax is straightforward. No parentheses required around the condition, but the colon is mandatory.
score = 72
if score >= 90:
print("A")
elif score >= 70:
print("C")
else:
print("F")
Conditions can use comparison operators, logical operators, in, not in, is, and is not.
Iterates over any iterable: lists, strings, dicts, ranges.
for i in range(5):
print(i)
for fruit in ["apple", "banana"]:
print(fruit)
range(start, stop, step) - stop is exclusive.
enumerate() gives both index and value:
for i, val in enumerate(["a", "b", "c"]):
print(i, val)
Runs as long as the condition is True. Use break to exit early, continue to skip to the next iteration, pass as a placeholder.
x = 0
while x < 5:
x += 1
if x == 3:
continue
print(x)
Infinite loops happen when the condition never becomes False. Always make sure something inside the loop changes the condition.
One-liner syntax for building lists. Faster than a regular for loop in most cases.
# Basic
squares = [x**2 for x in range(10)]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
# Nested
matrix = [[i * j for j in range(3)] for i in range(3)]
List comprehension syntax: [expression for item in iterable if condition]
The condition is optional. Nesting works but gets hard to read quickly - keep it to two levels max.
Functions are defined with def. No function body means a SyntaxError - use pass as a placeholder if needed.
def greet(name):
return f"Hello, {name}!"
Define once, call anywhere. Function names follow snake_case by convention (PEP 8).
def add(a, b):
return a + b
result = add(3, 5) # 8
Python gives you four ways to pass data into a function:
Positional - order matters: add(3, 5)
Keyword - name matters, order doesn't: add(b=5, a=3)
Default - fallback value if argument is omitted: def greet(name="user")
*args - variable positional arguments (tuple); **kwargs - variable keyword arguments (dict)
def log(*args, **kwargs):
print(args, kwargs)
log("error", code=404, path="/home")
Single-expression anonymous functions. Useful inline, terrible for anything complex.
square = lambda x: x ** 2
print(square(4)) # 16
Common use: passing a function as an argument to sorted(), map(), or filter().
A function without a return statement returns None. Multiple values can be returned as a tuple.
def min_max(lst):
return min(lst), max(lst)
lo, hi = min_max([3, 1, 9, 2])
No import needed. These ship with every Python 3 installation.
|
Function |
What it does |
|---|---|
|
|
Output to console |
|
|
Length of an object |
|
|
Generate a number sequence |
|
|
Return object type |
|
|
Read user input (returns str) |
|
|
Type conversion |
|
|
Convert to collection type |
|
|
Pair items from two iterables |
|
|
Apply function to iterable |
|
|
Filter iterable by condition |
|
|
Return sorted copy |
|
|
Add index to iterable |
|
|
Math on iterables |
|
|
Absolute value, rounding |
zip() stops at the shortest iterable. map() and filter() return iterators, not lists - wrap in list() to see the result.
import math
print(math.sqrt(16)) # 4.0
from math import sqrt
print(sqrt(16)) # 4.0
import numpy as np # aliased import
from module import * pulls everything into the namespace. Avoid it - name collisions are a pain to debug.
No pip install needed. Part of Python's standard library.
os - file system operations, environment variables
sys - interpreter info, command-line args (sys.argv)
math - sqrt, ceil, floor, pi, log
random - random(), randint(), choice(), shuffle()
datetime - dates, times, timedeltas
json - parse and serialize JSON
re - regular expressions
collections - Counter, defaultdict, deque, OrderedDict
f = open("file.txt", "r")
content = f.read()
f.close()
Always close the file. Or better, use with - it closes automatically.
with open("output.txt", "w") as f:
f.write("Hello\n")
"w" overwrites. "a" appends. Both create the file if it doesn't exist.
with open() is the standard pattern. Handles closing even if an exception is raised mid-operation.
with open("data.txt", "r") as f:
for line in f:
print(line.strip())
|
Mode |
Behavior |
|---|---|
|
|
Read (default) |
|
|
Write, overwrite |
|
|
Append |
|
|
Binary read/write |
|
|
Read and write |
Binary mode (rb, wb) is needed for images, PDFs, and other non-text files.
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
else:
print("No error")
finally:
print("Always runs")
else runs only if no exception was raised. finally runs regardless - useful for cleanup.
ValueError - right type, wrong value (int("abc"))
TypeError - wrong type entirely ("text" + 5)
KeyError - missing dict key
IndexError - list index out of range
AttributeError - attribute doesn't exist on the object
FileNotFoundError - file path doesn't exist
Catch specific exceptions, not bare except:. Bare except catches everything including KeyboardInterrupt.
def set_age(age):
if age < 0:
raise ValueError("Age can't be negative")
return age
Use raise to enforce constraints. Custom exception classes inherit from Exception.
Python is multi-paradigm. OOP is optional, but understanding it is necessary for working with most Python libraries and frameworks.
class Dog:
species = "Canis familiaris" # class attribute
def __init__(self, name, age):
self.name = name # instance attribute
self.age = age
__init__ runs automatically when an instance is created. self refers to the instance - it must be the first parameter of every instance method, but you don't pass it explicitly when calling.
rex = Dog("Rex", 4)
print(rex.name) # Rex
Instance methods - access self; most common
@classmethod - access cls; used for alternative constructors
@staticmethod - no access to instance or class; utility functions
class Circle:
def area(self):
return 3.14 * self.radius ** 2
@classmethod
def from_diameter(cls, d):
return cls(d / 2)
@staticmethod
def is_valid_radius(r):
return r > 0
class Animal:
def speak(self):
return "..."
class Cat(Animal):
def speak(self):
return "Meow"
Child classes override parent methods. super() calls the parent's version.
Also called dunder methods. Python calls them automatically in specific contexts.
__str__ - called by print() and str()
__repr__ - unambiguous representation, used in the REPL
__len__ - called by len()
__eq__ - defines == behavior
__init__ - constructor
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return self.title
def __repr__(self):
return f"Book('{self.title}')"
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
Faster than for loops for simple transformations. Harder to read past two conditions.
word_lengths = {word: len(word) for word in ["python", "code", "cheat"]}
inverted = {v: k for k, v in original.items()}
Dictionary comprehension follows the same pattern as list comprehension, with {key: value for ...}.
matrix = [[i * j for j in range(3)] for i in range(3)]
flat = [x for row in matrix for x in row]
Keep nesting to two levels. Beyond that, use a regular loop.
Three approaches exist. f-strings are the modern standard.
name = "Alex"
score = 98.5
print(f"{name} scored {score:.1f}") # Alex scored 98.5
Supports expressions, method calls, and format specifiers inside {}. Fastest of the three options.
"{} scored {}".format("Alex", 98.5)
"{name} scored {score}".format(name="Alex", score=98.5)
Still widely used in older codebases. Works in Python 2 and 3.
"Hello, %s. You are %d years old." % ("Alex", 30)
Old-style C formatting. Still works but avoid it in new code.
import re
All regex operations go through the re module. Patterns are raw strings (r"pattern") to avoid backslash conflicts.
|
Pattern |
Matches |
|---|---|
|
|
Any character except newline |
|
|
Digit (0-9) |
|
|
Word character (letters, digits, |
|
|
Whitespace |
|
|
Start of string |
|
|
End of string |
|
|
0 or more |
|
|
1 or more |
|
|
0 or 1 (optional) |
|
|
Between n and m times |
re.match() - matches at the start of the string only
re.search() - scans the whole string, returns first match
re.findall() - returns all matches as a list
re.sub(pattern, replacement, string) - find and replace
text = "Order #1042 placed on 2024-03-15"
dates = re.findall(r"\d{4}-\d{2}-\d{2}", text)
clean = re.sub(r"#\d+", "[ID]", text)
sorted() returns a new list. .sort() modifies in place and returns None.
nums = [3, 1, 4, 1, 5]
print(sorted(nums)) # [1, 1, 3, 4, 5] - original unchanged
nums.sort(reverse=True) # [5, 4, 3, 1, 1] - modified in place
users = [{"name": "Bob", "age": 25}, {"name": "Ana", "age": 30}]
users.sort(key=lambda x: x["age"])
words = ["banana", "fig", "apple"]
words.sort(key=len)
The key parameter accepts any callable. Works with both sorted() and .sort().
nums = [10, 20, 30]
print(20 in nums) # True - membership test
print(nums.index(30)) # 2 - index of first match
data = {"user": "Alex"}
print("user" in data) # True - checks keys
print("Alex" in data.values()) # True - checks values
in on a list is O(n). in on a set or dict is O(1). For large datasets, convert to a set first.
python -m venv env
source env/bin/activate # macOS/Linux
env\Scripts\activate # Windows
Virtual environments isolate project dependencies. Without one, packages install globally and version conflicts become a real problem.
pip install requests
pip install django==4.2.0 # specific version
pip uninstall requests
pip list # show installed packages
pip show requests # details on one package
pip pulls from PyPI (Python Package Index). Most Python libraries live there, including Requests, Matplotlib, and NumPy.
pip freeze > requirements.txt # save current environment
pip install -r requirements.txt # recreate environment
Commit requirements.txt to version control. Skip the env/ folder itself - it's machine-specific and usually large.
A solid Python cheat sheet covers syntax basics, data types, built-in functions, control flow, and string methods.
Include operators, list and dictionary comprehensions, file handling, and error handling. The more complete the reference, the less time you spend searching Stack Overflow.
Lists are mutable. Tuples are immutable - once created, values can't change.
Use lists when data needs to change; use tuples for fixed data like coordinates or database records. Tuples are slightly faster to iterate.
Use try, except, else, and finally blocks.
Catch specific exceptions like ValueError or KeyError rather than a bare except. Bare except catches everything, including keyboard interrupts, which causes harder-to-diagnose bugs.
f-strings (Python 3.6+) are the fastest and most readable string formatting option.
Write f"{variable}" to insert values directly into a string. They support expressions, method calls, and format specifiers inside the curly braces. Use them by default.
sorted() and .sort() in Python?sorted() returns a new list and leaves the original unchanged. .sort() modifies the list in place and returns None.
Both accept a key parameter for custom sorting logic.
A virtual environment isolates project dependencies so packages don't conflict across projects.
Create one with python -m venv env, activate it, then install packages with pip. Always add requirements.txt to version control using pip freeze.
len(), range(), zip(), enumerate(), sorted(), map(), and filter() cover most everyday use cases.
None require an import. enumerate() is the one beginners skip most often - it gives both index and value in a single loop.
List comprehension is a one-line syntax for building lists: [expression for item in iterable if condition].
It's faster than a standard for loop for simple transformations. Dictionary and set comprehensions follow the same pattern with minor syntax changes.
Start with os, sys, math, random, datetime, and json - all part of Python's standard library, no pip install needed.
For data work, add NumPy and Pandas. For web projects, Requests and Flask or Django cover most needs.
== and is in Python?== compares values. is compares object identity - whether two variables point to the exact same object in memory.
"hello" == "hello" is True. Whether "hello" is "hello" is True depends on Python's string interning. Don't use is for value comparisons.