📖 Guide
Python Cheat Sheet — Complete Reference
Complete Python reference covering syntax, data structures, string methods, file I/O, comprehensions, and common patterns.
163 commands across 13 categories
BasicsStringsListsDictionariesSets & TuplesControl FlowFunctionsClasses & OOPFile I/OError HandlingComprehensionsModules & ImportsCommon Built-ins
Basics
| Command | Description |
|---|---|
x = 10 | Assign a value to a variable |
x, y, z = 1, 2, 3 | Multiple assignment in one line |
type(x)e.g. type(42) # <class 'int'> | Get the type of a variable |
isinstance(x, int)e.g. isinstance('hi', str) # True | Check if a variable is an instance of a type |
print()e.g. print("Hello", "World", sep=", ", end="!\n") | Print output to the console |
input()e.g. name = input("Enter your name: ") | Read a string from user input |
int(), float(), str(), bool()e.g. int("42") # 42
float("3.14") # 3.14 | Type casting / conversion functions |
# comment | Single-line comment |
"""docstring""" | Multi-line string or docstring |
None | Python's null value — represents absence of a value |
del x | Delete a variable or item |
id(x) | Get the memory address (identity) of an object |
Strings
| Command | Description |
|---|---|
f"Hello {name}"e.g. f"Total: {price * 1.2:.2f}" | F-string — inline expression interpolation |
s.upper() / s.lower() | Convert string to uppercase or lowercase |
s.strip() | Remove leading/trailing whitespace |
s.lstrip() / s.rstrip() | Remove whitespace from left or right only |
s.split(sep)e.g. "a,b,c".split(",") # ['a', 'b', 'c'] | Split string into a list by separator |
sep.join(iterable)e.g. ", ".join(["a", "b", "c"]) # "a, b, c" | Join a list of strings with a separator |
s.replace(old, new)e.g. "hello world".replace("world", "python") | Replace occurrences of a substring |
s.startswith(prefix) / s.endswith(suffix) | Check if string starts or ends with a substring |
s.find(sub) | Find index of first occurrence (-1 if not found) |
s.count(sub) | Count occurrences of a substring |
s.isdigit() / s.isalpha() / s.isalnum() | Check if string contains only digits, letters, or both |
s.title() / s.capitalize() | Title Case or Capitalize first letter |
s.zfill(width)e.g. "42".zfill(5) # "00042" | Pad string with zeros on the left |
s[start:stop:step]e.g. "hello"[1:4] # "ell"
"hello"[::-1] # "olleh" | Slice a string |
len(s) | Get the length of a string |
s.encode() / b.decode()e.g. "hello".encode("utf-8") | Encode string to bytes / decode bytes to string |
Lists
| Command | Description |
|---|---|
lst = [1, 2, 3] | Create a list |
lst.append(item) | Add an item to the end of the list |
lst.extend(iterable)e.g. [1, 2].extend([3, 4]) # [1, 2, 3, 4] | Add all items from another iterable |
lst.insert(index, item)e.g. lst.insert(0, 'first') | Insert an item at a specific index |
lst.remove(item) | Remove first occurrence of item (raises ValueError if missing) |
lst.pop(index)e.g. last = lst.pop()
first = lst.pop(0) | Remove and return item at index (default: last) |
lst.clear() | Remove all items from the list |
lst.index(item) | Find index of first occurrence |
lst.count(item) | Count occurrences of an item |
lst.sort(key=None, reverse=False)e.g. lst.sort(key=lambda x: x.lower(), reverse=True) | Sort the list in place |
sorted(lst) | Return a new sorted list (original unchanged) |
lst.reverse() | Reverse the list in place |
lst.copy() / lst[:] | Create a shallow copy of the list |
lst[start:stop:step]e.g. lst[::2] # every other item | Slice a list |
len(lst) | Get the number of items in a list |
item in lst | Check membership |
list(zip(a, b))e.g. list(zip([1,2], ['a','b'])) # [(1,'a'), (2,'b')] | Combine two lists into pairs |
list(range(start, stop, step))e.g. list(range(0, 10, 2)) # [0, 2, 4, 6, 8] | Generate a list of numbers |
Dictionaries
| Command | Description |
|---|---|
d = {"key": "value"} | Create a dictionary |
d[key] | Access a value by key (raises KeyError if missing) |
d.get(key, default)e.g. d.get("missing", 0) # 0 | Get a value with a default if key is missing |
d[key] = value | Set or update a key-value pair |
d.setdefault(key, default) | Get value if key exists, otherwise set it to default and return |
d.update(other_dict) | Merge another dict into this one (overwrites existing keys) |
{**d1, **d2}e.g. merged = {**defaults, **overrides} | Merge dicts using unpacking (Python 3.5+) |
d1 | d2 | Merge dicts with union operator (Python 3.9+) |
del d[key] | Delete a key-value pair |
d.pop(key, default) | Remove and return value for key |
d.keys() / d.values() / d.items() | Get views of keys, values, or key-value pairs |
key in d | Check if key exists in dictionary |
len(d) | Get the number of key-value pairs |
dict.fromkeys(keys, value)e.g. dict.fromkeys(["a","b","c"], 0) # {"a":0, "b":0, "c":0} | Create a dict with given keys and a default value |
for k, v in d.items(): | Iterate over key-value pairs |
{k: v for k, v in iterable}e.g. {x: x**2 for x in range(5)} | Dictionary comprehension |
Sets & Tuples
| Command | Description |
|---|---|
s = {1, 2, 3} | Create a set (unordered, unique items) |
set() | Create an empty set (not {} which creates a dict) |
s.add(item) | Add an item to the set |
s.discard(item) | Remove an item (no error if missing) |
s.remove(item) | Remove an item (raises KeyError if missing) |
s1 | s2 / s1.union(s2) | Union of two sets |
s1 & s2 / s1.intersection(s2) | Intersection of two sets |
s1 - s2 / s1.difference(s2) | Items in s1 but not in s2 |
s1 ^ s2 / s1.symmetric_difference(s2) | Items in either set but not both |
s1.issubset(s2) / s1 <= s2 | Check if s1 is a subset of s2 |
t = (1, 2, 3) | Create a tuple (immutable sequence) |
t = (42,) | Create a single-element tuple (trailing comma required) |
a, b, c = t | Unpack a tuple into variables |
a, *rest = te.g. a, *rest = (1, 2, 3, 4) # a=1, rest=[2,3,4] | Unpack with starred expression |
from collections import namedtuplee.g. Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)
print(p.x) | Create a named tuple type for readable tuples |
Control Flow
| Command | Description |
|---|---|
if / elif / elsee.g. if x > 0:
print('positive')
elif x == 0:
print('zero')
else:
print('negative') | Conditional branching |
x if condition else ye.g. status = "even" if n % 2 == 0 else "odd" | Ternary / conditional expression |
for item in iterable: | Iterate over items in a sequence |
for i, item in enumerate(lst):e.g. for i, name in enumerate(["a","b","c"]):
print(i, name) | Loop with index and value |
for i in range(n): | Loop a specific number of times |
while condition: | Loop while a condition is true |
break | Exit the innermost loop immediately |
continue | Skip to the next iteration of the loop |
pass | No-op placeholder (empty block) |
match value:e.g. match command:
case "quit":
exit()
case "hello":
greet()
case _:
print("unknown") | Structural pattern matching (Python 3.10+) |
Functions
| Command | Description |
|---|---|
def fn(arg1, arg2): | Define a function |
def fn(arg=default):e.g. def greet(name="World"):
return f"Hello {name}" | Function with default parameter value |
def fn(*args): | Accept any number of positional arguments as a tuple |
def fn(**kwargs): | Accept any number of keyword arguments as a dict |
def fn(*, key_only): | Force keyword-only arguments (after *) |
def fn(pos_only, /): | Force positional-only arguments (before /) |
return value | Return a value from a function |
return a, b | Return multiple values as a tuple |
lambda x: x * 2e.g. double = lambda x: x * 2
sorted(lst, key=lambda x: x[1]) | Anonymous / inline function |
def fn() -> int: | Type hint for return value |
def fn(x: int, y: str = 'hi') -> bool: | Full type hints on function signature |
@decoratore.g. @lru_cache(maxsize=128)
def fib(n):
... | Apply a decorator to a function |
yield valuee.g. def counter(n):
for i in range(n):
yield i | Turn a function into a generator |
Classes & OOP
| Command | Description |
|---|---|
class MyClass: | Define a class |
def __init__(self, ...):e.g. class Dog:
def __init__(self, name):
self.name = name | Constructor / initializer method |
self.attr = value | Set an instance attribute |
class Child(Parent): | Inheritance — create a subclass |
super().__init__() | Call parent class constructor |
def __str__(self): | String representation for print() and str() |
def __repr__(self): | Developer string representation for debugging |
def __len__(self): | Support len() on your class |
def __eq__(self, other): | Define equality comparison (==) |
@propertye.g. @property
def area(self):
return self.width * self.height | Define a computed attribute (getter) |
@staticmethod | Define a method that doesn't need self or cls |
@classmethod | Define a method that receives the class as first argument |
@dataclasse.g. from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float | Auto-generate __init__, __repr__, __eq__ etc. |
File I/O
| Command | Description |
|---|---|
open(path, "r") | Open a file for reading (default mode) |
with open(path) as f:
content = f.read() | Read entire file using context manager (auto-closes) |
f.readlines() | Read all lines into a list |
for line in f: | Iterate over lines one at a time (memory efficient) |
with open(path, "w") as f:
f.write(text) | Write to a file (overwrites existing content) |
with open(path, "a") as f:
f.write(text) | Append to a file |
open(path, "rb") / open(path, "wb") | Open in binary mode for non-text files |
from pathlib import Pathe.g. p = Path("data/file.txt")
p.read_text()
p.write_text("hello")
p.exists()
p.mkdir(parents=True) | Modern file path handling |
Path.glob(pattern)e.g. list(Path(".").glob("**/*.py")) # all Python files recursively | Find files matching a pattern |
import json
json.loads(s) / json.dumps(obj) | Parse and serialize JSON strings |
json.load(f) / json.dump(obj, f)e.g. with open("data.json") as f:
data = json.load(f) | Read/write JSON from/to files |
import csv
csv.reader(f) / csv.DictReader(f) | Read CSV files row by row or as dictionaries |
Error Handling
| Command | Description |
|---|---|
try / excepte.g. try:
result = 10 / 0
except ZeroDivisionError:
print('Cannot divide by zero') | Catch and handle exceptions |
except Exception as e:e.g. except ValueError as e:
print(f"Error: {e}") | Catch exception and access the error object |
except (TypeError, ValueError): | Catch multiple exception types |
try / except / else | else block runs if no exception occurred |
try / except / finally | finally block always runs (cleanup code) |
raise ValueError(msg) | Raise an exception manually |
raise ... from originale.g. raise RuntimeError('failed') from original_error | Chain exceptions to preserve the original cause |
class MyError(Exception): pass | Define a custom exception class |
assert condition, messagee.g. assert len(items) > 0, "List cannot be empty" | Assert a condition (raises AssertionError if false) |
Comprehensions
| Command | Description |
|---|---|
[expr for x in iterable]e.g. [x**2 for x in range(10)] | List comprehension |
[expr for x in iterable if condition]e.g. [x for x in range(20) if x % 3 == 0] | List comprehension with filter |
[expr if cond else other for x in iterable]e.g. ["even" if x%2==0 else "odd" for x in range(5)] | Conditional expression in list comprehension |
{expr for x in iterable}e.g. {len(word) for word in words} | Set comprehension |
{k: v for k, v in iterable}e.g. {name: len(name) for name in names} | Dictionary comprehension |
(expr for x in iterable)e.g. sum(x**2 for x in range(1000000)) | Generator expression (lazy, memory efficient) |
[expr for x in outer for y in inner]e.g. [c for word in words for c in word] | Nested comprehension (flattening) |
Modules & Imports
| Command | Description |
|---|---|
import modulee.g. import os | Import an entire module |
from module import namee.g. from pathlib import Path | Import a specific name from a module |
from module import name as aliase.g. import numpy as np | Import with an alias |
from module import * | Import all public names (avoid in production code) |
if __name__ == "__main__": | Run code only when file is executed directly (not imported) |
__all__ = [...] | Define what gets exported with 'from module import *' |
import importlib
importlib.reload(module) | Reload a module at runtime |
import sys
sys.path.append(dir) | Add a directory to the module search path |
Common Built-ins
| Command | Description |
|---|---|
map(fn, iterable)e.g. list(map(str.upper, ['a','b','c'])) | Apply a function to every item |
filter(fn, iterable)e.g. list(filter(lambda x: x > 0, [-1, 0, 1, 2])) | Keep items where fn returns True |
zip(iter1, iter2, ...) | Pair up items from multiple iterables |
enumerate(iterable, start=0) | Yield (index, item) pairs |
any(iterable) / all(iterable)e.g. any([False, True, False]) # True
all([True, True, True]) # True | True if any/all items are truthy |
min(iterable) / max(iterable)e.g. max(words, key=len) # longest word | Find minimum or maximum value |
sum(iterable, start=0) | Sum all items in an iterable |
abs(x) | Absolute value |
round(x, ndigits)e.g. round(3.14159, 2) # 3.14 | Round to n decimal places |
reversed(seq) | Return a reversed iterator |
hash(obj) | Get hash value of an object |
dir(obj) | List all attributes and methods of an object |
help(obj) | Show documentation for an object |
globals() / locals() | Get current global or local symbol table as a dict |
📖 Free, searchable command reference. Bookmark this page for quick access.