← Home

Python Cheatsheet

A comprehensive quick-reference for Python — data types, string methods, list and dict operations, control flow, functions, file I/O, and essential patterns. All with real code examples you can copy straight into your editor.

Data Types

CodeDescription
x = 42int — arbitrary-precision integer
pi = 3.14159float — 64-bit double-precision floating point
z = 2 + 3jcomplex — complex number with real and imaginary parts
s = "hello"str — immutable Unicode text sequence
flag = Truebool — True or False (subclass of int)
items = [1, 2, 3]list — ordered, mutable sequence
point = (1, 2, 3)tuple — ordered, immutable sequence
person = {"name": "Jo"}dict — key-value mapping, insertion-ordered (3.7+)
unique = {1, 2, 3}set — unordered collection of unique hashable elements
frozen = frozenset({1, 2})frozenset — immutable set, can be used as dict key
data = bytes(b'\xff')bytes — immutable sequence of bytes
buf = bytearray(10)bytearray — mutable sequence of bytes
nothing = NoneNoneType — singleton representing absence of a value
int('42')Convert string to int — raises ValueError if invalid
float('3.14')Convert string to float
str(42)Convert any object to its string representation
bool(0) # FalseFalsy: 0, 0.0, '', [], {}, set(), None — everything else truthy
list((1, 2, 3))Convert iterable to list
tuple([1, 2, 3])Convert iterable to tuple
set([1, 1, 2])Convert iterable to set (removes duplicates)
dict(a=1, b=2)Create dict from keyword arguments
type(x)Return the type of an object
isinstance(x, int)Check if object is an instance of a type (or tuple of types)

String Methods

CodeDescription
"a,b,c".split(",")Split string into list by delimiter — ['a', 'b', 'c']
",".join(["a","b"])Join iterable into string with separator — 'a,b'
" hi ".strip()Remove leading/trailing whitespace (lstrip, rstrip for one side)
"hello".replace("l","r")Replace all occurrences of substring — 'herro'
"hello world".find("world")Return index of first occurrence, or -1 if not found
"hello world".index("world")Like find() but raises ValueError if not found
"hello".upper()Convert to uppercase — 'HELLO'
"HELLO".lower()Convert to lowercase — 'hello'
"hello world".title()Capitalize first letter of each word — 'Hello World'
"hello world".capitalize()Capitalize first character only — 'Hello world'
"hello".startswith("he")Check if string starts with prefix — True
"hello".endswith("lo")Check if string ends with suffix — True
"hello".count("l")Count non-overlapping occurrences of substring — 2
"{} is {}".format("sky","blue")Positional format — 'sky is blue'
f"pi is {3.14:.1f}"f-string with format spec — 'pi is 3.1'
f"{name!r}"f-string with !r (repr), !s (str), !a (ascii) conversions
"hello"[1:4]Slice — 'ell' (start inclusive, end exclusive)
"hello"[::-1]Reverse a string via slice — 'olleh'
"42".isdigit()Check if all characters are digits — True
"abc".isalpha()Check if all characters are alphabetic — True
"abc123".isalnum()Check if all characters are alphanumeric — True
"hello".center(20, "-")Center string with fill char — '-------hello--------'
"hello".ljust(10, ".")Left-justify with fill — 'hello.....'
"5".zfill(3)Pad with leading zeros — '005'
"a\nb\nc".splitlines()Split by line boundaries — ['a', 'b', 'c']

List Operations

CodeDescription
lst.append(4)Add single element to end of list
lst.extend([5, 6])Extend list by appending all items from iterable
lst.insert(0, 'first')Insert element at a specific index
lst.remove('x')Remove first occurrence of value — raises ValueError if absent
lst.pop()Remove and return last element (or at index if given)
lst.pop(0)Remove and return first element — O(n) operation
lst.sort()Sort in place ascending (key= and reverse= kwargs)
sorted(lst, key=len)Return new sorted list — original unchanged
lst.reverse()Reverse the list in place
lst[::-1]Return new reversed list via slicing
[x**2 for x in range(5)]List comprehension — [0, 1, 4, 9, 16]
[x for x in lst if x > 0]Filtered comprehension — keep only positives
lst[1:4]Slice from index 1 up to (not including) 4
lst[::2]Every 2nd element via step slice
for i, v in enumerate(lst):Loop with index and value
for a, b in zip(x, y):Loop over two lists in parallel
lst.index('x')Find index of first occurrence — ValueError if missing
lst.count(42)Count occurrences of a value
lst.copy()Shallow copy of the list
import copy; copy.deepcopy(lst)Deep copy — recursively copies nested objects
lst.clear()Remove all items from the list
len(lst)Number of elements in the list
'x' in lstMembership test — True if 'x' is in the list
list(map(str, [1,2,3]))Apply function to each element — ['1','2','3']
list(filter(None, lst))Remove falsy values from list
sum(lst)Sum of all elements (numeric list)
min(lst), max(lst)Minimum and maximum values

Dictionary Methods

CodeDescription
d.get("key", default)Get value by key, return default if missing (no error)
d.keys()View of all keys — iterable, reflects changes
d.values()View of all values
d.items()View of all (key, value) tuples — great for iteration
d.update({"a": 1})Merge another dict into this one — overwrites existing keys
d | otherMerge operator (3.9+) — returns new dict
d |= otherIn-place merge operator (3.9+)
d.pop("key")Remove key and return its value — KeyError if missing
d.pop("key", None)Remove key, return None instead of error if missing
d.popitem()Remove and return last inserted (key, value) pair
d.setdefault("k", [])Return value if key exists, else set to default and return it
{k: v**2 for k, v in d.items()}Dict comprehension — transform values
{v: k for k, v in d.items()}Invert a dict — swap keys and values
dict.fromkeys(['a','b'], 0)Create dict with given keys, all set to same value
from collections import defaultdictImport defaultdict for auto-initializing values
dd = defaultdict(list)Missing keys auto-initialize as empty lists
from collections import CounterImport Counter for counting hashable objects
Counter('abracadabra')Count characters — Counter({'a':5, 'b':2, ...})
from collections import OrderedDictDict that remembers insertion order (pre-3.7 compat)
"key" in dCheck if key exists in dict — O(1) average
del d['key']Delete key-value pair — KeyError if missing
len(d)Number of key-value pairs
d.copy()Shallow copy of the dictionary
d.clear()Remove all items from the dictionary

Control Flow

CodeDescription
if x > 0:Execute block if condition is true
elif x == 0:Check additional condition if prior if/elif was false
else:Execute block if no preceding condition was true
for item in iterable:Iterate over elements of any iterable
for i in range(10):Loop with counter — range(start, stop, step)
for i in range(0, 10, 2):Loop with step — 0, 2, 4, 6, 8
for i, v in enumerate(lst):Loop with index — enumerate(iterable, start=0)
for a, b in zip(xs, ys):Parallel iteration over multiple iterables
while condition:Loop while condition is true
while True: ... breakInfinite loop with explicit break
breakExit the innermost loop immediately
continueSkip to next iteration of the innermost loop
passNo-op placeholder — use in empty blocks
for ... else:else block runs if loop completes without break
match command:Structural pattern matching (3.10+)
case "quit":Match exact value in match/case
case [x, y]:Destructure sequence in match/case
case {'key': v}:Match dict pattern in match/case
case _:Wildcard — matches anything (default branch)
x if cond else yTernary / conditional expression
any(x > 0 for x in lst)True if any element satisfies condition
all(x > 0 for x in lst)True if all elements satisfy condition

Functions

CodeDescription
def greet(name):Define a function with parameter
def add(a, b): return a + bSingle-expression function with return
def greet(name="World"):Parameter with default value
def f(*args):Accept any number of positional arguments as tuple
def f(**kwargs):Accept any number of keyword arguments as dict
def f(a, b, /, c, *, d):Positional-only (before /) and keyword-only (after *)
lambda x: x * 2Anonymous function — single expression, implicit return
lambda x, y: x + yMulti-parameter lambda
map(lambda x: x**2, lst)Apply lambda to each element (returns iterator)
filter(lambda x: x>0, lst)Keep elements where lambda returns True
from functools import reduceImport reduce for cumulative operations
reduce(lambda a,b: a+b, lst)Reduce iterable to single value — left fold
@decoratorApply decorator to function (wraps it)
def deco(fn): ...; return wrapperDecorator pattern — function that returns a wrapper
@functools.lru_cacheMemoize function results (built-in caching decorator)
def f(x: int) -> str:Type hints — annotations for parameters and return
def f(x: list[int]):Generic type hint (3.9+ built-in generics)
def f(x: int | None):Union type hint (3.10+ syntax)
def gen(): yield 1; yield 2Generator function — yields values lazily
next(gen())Retrieve next value from generator/iterator
def gen(): yield from other()Delegate to sub-generator
(x**2 for x in range(10))Generator expression — lazy, memory-efficient
global varDeclare variable as global inside function
nonlocal varReference enclosing scope variable in nested function

File I/O

CodeDescription
open("f.txt", "r")Open file for reading (default mode)
open("f.txt", "w")Open for writing — creates or truncates file
open("f.txt", "a")Open for appending — writes to end of file
open("f.txt", "rb")Open in binary read mode
with open("f.txt") as f:Context manager — auto-closes file on exit
f.read()Read entire file contents as string
f.readline()Read one line (including newline character)
f.readlines()Read all lines into a list
for line in f:Iterate over file line by line (memory efficient)
f.write("text")Write string to file — returns number of chars written
f.writelines(["a\n","b\n"])Write list of strings — does not add newlines
from pathlib import PathImport modern path handling library
p = Path("dir/file.txt")Create Path object — cross-platform paths
p.read_text()Read entire file as string (auto open/close)
p.write_text("data")Write string to file (auto open/close)
p.exists()Check if path exists
p.is_file(), p.is_dir()Check if path is a file or directory
p.mkdir(parents=True)Create directory and any missing parents
p.stem, p.suffix, p.nameParts: 'file', '.txt', 'file.txt'
list(Path('.').glob('*.py'))Find all .py files in directory
list(Path('.').rglob('*.py'))Recursively find all .py files
import csvImport CSV reader/writer module
csv.reader(f)Read CSV file as rows of lists
csv.DictReader(f)Read CSV rows as dictionaries (header keys)
import jsonImport JSON module
json.load(f)Parse JSON from file object
json.loads('{"a":1}')Parse JSON from string
json.dump(obj, f, indent=2)Write object to file as formatted JSON
json.dumps(obj)Serialize object to JSON string

Common Patterns

CodeDescription
try: ... except Exception as e:Catch exceptions — use specific types when possible
except (TypeError, ValueError):Catch multiple exception types
except Exception as e: raiseCatch, log, then re-raise the same exception
finally:Always runs — cleanup code (close connections, etc.)
else: # after tryRuns only if no exception was raised in try block
raise ValueError('msg')Raise an exception explicitly
[x**2 for x in range(10)]List comprehension — concise list building
{k: v for k, v in pairs}Dict comprehension from iterable of pairs
{x for x in lst if x > 0}Set comprehension — unique filtered values
val = a if cond else bTernary expression — inline conditional
if (n := len(lst)) > 10:Walrus operator := — assign and test in one expression
while chunk := f.read(8192):Walrus in loop — read until empty
a, b, *rest = [1,2,3,4,5]Extended unpacking — a=1, b=2, rest=[3,4,5]
first, *_, last = itemsCapture first and last, discard middle
a, b = b, aSwap variables without temp
d = {**d1, **d2}Merge dicts (3.5+) — d2 values overwrite d1
combined = [*list1, *list2]Unpack and merge lists
with open(a) as f1, open(b) as f2:Multiple context managers in one with statement
from contextlib import suppressImport suppress to silently ignore exceptions
with suppress(FileNotFoundError):Ignore specific exception in a block
from dataclasses import dataclassImport dataclass decorator
@dataclass class Point:Auto-generate __init__, __repr__, __eq__ from fields
from enum import EnumImport Enum for defining enumerations
assert x > 0, 'must be positive'Debug assertion — disabled with python -O
if __name__ == '__main__':Guard block — runs only when script is executed directly

FAQ

What Python version should I use in 2025?

Python 3.12+ is recommended for new projects. It includes performance improvements (up to 5% faster), better error messages, f-string enhancements, and support for the match/case syntax introduced in 3.10. Python 2 reached end-of-life in January 2020 and should not be used.

What is the difference between a list and a tuple?

Lists are mutable (you can add, remove, and change elements), while tuples are immutable (once created, they cannot be modified). Tuples are slightly faster, use less memory, and can be used as dictionary keys or set elements because they're hashable. Use lists when you need to modify the collection, and tuples for fixed data like coordinates or function return values.

How do f-strings work and why should I use them?

f-strings (formatted string literals) let you embed expressions inside string literals using curly braces: f"Hello {name}". They're evaluated at runtime, support format specs like f"{pi:.2f}", and can contain any valid Python expression. They're the fastest and most readable string formatting method, preferred over .format() and % formatting since Python 3.6.

What is the walrus operator := and when should I use it?

The walrus operator (:=), introduced in Python 3.8, assigns a value to a variable as part of an expression. For example, 'if (n := len(data)) > 10' both assigns len(data) to n and checks the condition. It's useful in while loops (while chunk := f.read(8192)), list comprehensions, and anywhere you'd otherwise need a separate assignment line before a condition.

Related Resources