Complete Python reference covering variables, data types, strings, lists, dictionaries, control flow, functions, classes, file I/O, error handling, comprehensions, and the standard library. With code examples for every section.
| Syntax / Example | Description |
x = 10 | Integer (int) — whole numbers, arbitrary precision |
pi = 3.14 | Float (float) — floating-point number (64-bit double) |
name = "Alice" | String (str) — immutable sequence of Unicode characters |
is_valid = True | Boolean (bool) — True or False |
nums = [1, 2, 3] | List (list) — mutable, ordered sequence |
info = {"key": "val"} | Dictionary (dict) — mutable key-value mapping |
point = (1, 2) | Tuple (tuple) — immutable ordered sequence |
unique = {1, 2, 3} | Set (set) — mutable, unordered, no duplicates |
nothing = None | None — represents the absence of a value |
type(x) | Return the type of x. type(42) → <class 'int'> |
isinstance(x, int) | Check if x is an instance of a type. Returns True or False |
int("42"), float("3.14"), str(99) | Type conversion / casting between types |
a, b, c = 1, 2, 3 | Multiple assignment (tuple unpacking) |
x, *rest = [1, 2, 3, 4] | Extended unpacking. x=1, rest=[2,3,4] |
| Method / Syntax | Description |
s.split(",") | Split string by delimiter. "a,b,c".split(",") → ["a","b","c"] |
",".join(lst) | Join list into string. ",".join(["a","b"]) → "a,b" |
s.strip() | Remove leading/trailing whitespace. Also lstrip(), rstrip() |
s.replace("old", "new") | Replace all occurrences. "hello".replace("l","L") → "heLLo" |
f"Hello {name}" | f-string (Python 3.6+). Inline expression evaluation |
f"{price:.2f}" | f-string with format spec. f"{3.1:.2f}" → "3.10" |
"Hi {}".format(name) | str.format() method. "Hi {}".format("Bob") → "Hi Bob" |
s.upper(), s.lower(), s.title() | Case conversion methods |
s.startswith("py") | Check prefix. Also endswith() |
s.find("sub") | Return index of substring or -1. s.index() raises ValueError |
s.count("a") | Count occurrences. "banana".count("a") → 3 |
s.isdigit(), s.isalpha() | Check character types. Also isalnum(), isspace() |
s.zfill(5) | Pad with zeros. "42".zfill(5) → "00042" |
s[1:4], s[::-1] | Slicing. "hello"[1:4] → "ell"; "hello"[::-1] → "olleh" |
| Method / Syntax | Description |
lst.append(item) | Add item to end. [1,2].append(3) → [1,2,3] |
lst.extend([4, 5]) | Add multiple items. [1,2].extend([3,4]) → [1,2,3,4] |
lst.insert(1, "x") | Insert at index. [1,3].insert(1, 2) → [1,2,3] |
lst.remove("x") | Remove first occurrence. Raises ValueError if not found |
lst.pop() | Remove and return last item. pop(0) removes first |
lst.pop(i) | Remove and return item at index i |
lst[1:3] | Slice. [10,20,30,40][1:3] → [20,30] |
lst[::2] | Step slice. [1,2,3,4,5][::2] → [1,3,5] |
lst[::-1] | Reverse via slice. [1,2,3][::-1] → [3,2,1] |
lst.sort() | Sort in place (ascending). sort(reverse=True) for descending |
sorted(lst) | Return new sorted list. Original unchanged |
lst.reverse() | Reverse list in place |
lst.index("x") | Return index of first occurrence. Raises ValueError if not found |
lst.count(val) | Count occurrences of val |
lst.copy() | Shallow copy. Equivalent to lst[:] |
len(lst) | Return number of elements |
[x**2 for x in range(5)] | List comprehension. → [0, 1, 4, 9, 16] |
| Method / Syntax | Description |
d = {"a": 1, "b": 2} | Create a dictionary with key-value pairs |
d["key"] | Access value. Raises KeyError if key missing |
d.get("key", default) | Access with default. d.get("x", 0) → 0 if "x" not in d |
d.keys() | Return view of all keys. list(d.keys()) → ["a", "b"] |
d.values() | Return view of all values. list(d.values()) → [1, 2] |
d.items() | Return view of (key, value) pairs. Useful for iteration |
d.update({"c": 3}) | Merge another dict. d.update(other) adds/overwrites keys |
d | other | Merge operator (Python 3.9+). Returns new dict |
d |= other | In-place merge operator (Python 3.9+) |
d.pop("key") | Remove key and return value. pop("key", default) avoids KeyError |
d.setdefault("key", val) | Return d["key"] if exists, else set to val and return it |
del d["key"] | Delete key-value pair. Raises KeyError if missing |
"key" in d | Check if key exists. "a" in {"a":1} → True |
{k: v for k, v in items} | Dict comprehension. {x: x**2 for x in range(4)} → {0:0, 1:1, 2:4, 3:9} |
dict(zip(keys, vals)) | Create dict from two lists. dict(zip(["a","b"], [1,2])) → {"a":1, "b":2} |
| Syntax | Description |
if x > 0: print("pos") | Basic if statement. Indentation defines the block |
if x > 0: ... elif x == 0: ... else: ... | if / elif / else chain. Can have multiple elif branches |
y = "pos" if x > 0 else "neg" | Ternary / conditional expression (inline if-else) |
for item in iterable: | Iterate over any iterable (list, tuple, string, range, etc.) |
for i in range(5): | Loop 0 to 4. range(2, 8) → 2..7. range(0, 10, 2) → even numbers |
for i, val in enumerate(lst): | Loop with index and value. enumerate(lst, start=1) for 1-based |
for k, v in d.items(): | Iterate over dictionary key-value pairs |
while condition: | Loop while condition is True |
break | Exit the innermost loop immediately |
continue | Skip to the next iteration of the loop |
pass | No-op placeholder. Used for empty blocks |
for ... else: | The else block runs if the loop completes without break |
match value: case 1: ... case _: ... | Structural pattern matching (Python 3.10+). _ is the wildcard |
| Syntax | Description |
def greet(name): return f"Hi {name}" | Define a function with def. return sends back a value |
def add(a, b=0): | Default parameter value. add(5) → b defaults to 0 |
def func(*args): | Variadic positional args as a tuple. func(1,2,3) → args=(1,2,3) |
def func(**kwargs): | Variadic keyword args as a dict. func(a=1) → kwargs={"a":1} |
def func(a, *, key): | Keyword-only arguments. key must be passed as func(1, key=2) |
lambda x, y: x + y | Anonymous function. (lambda x: x*2)(5) → 10 |
def outer(): def inner(): ... return inner | Closure. Inner function captures variables from outer scope |
@decorator def func(): ... | Decorator syntax. Wraps func with decorator(func) |
def gen(n): for i in range(n): yield i | Generator function. Yields values lazily with yield |
next(gen_obj) | Get next value from a generator. Raises StopIteration at end |
def func(x: int) -> str: | Type hints (annotations). Not enforced at runtime |
"""Docstring here.""" | First string in function body — used by help(func) |
| Syntax | Description |
with open("f.txt") as f: data = f.read() | Read entire file. with ensures file is closed automatically |
f.readlines() | Read all lines into a list. Each line includes \n |
for line in f: | Iterate over file line by line (memory-efficient) |
with open("f.txt", "w") as f: f.write("hello") | Write to file. "w" overwrites, "a" appends |
f.writelines(lines) | Write a list of strings. Does not add newlines automatically |
open("f.txt", "r", encoding="utf-8") | Specify encoding. Always use encoding="utf-8" for text files |
open("img.png", "rb") | Read binary file. "wb" to write binary |
import json data = json.load(f) | Parse JSON from file. json.loads(s) parses from string |
json.dump(obj, f, indent=2) | Write JSON to file. json.dumps(obj) returns string |
import csv reader = csv.reader(f) | Read CSV file. csv.DictReader(f) returns dicts per row |
writer = csv.writer(f) writer.writerow([1, 2]) | Write CSV rows. csv.DictWriter for dict-based rows |
from pathlib import Path p = Path("file.txt") | Modern path handling. p.read_text(), p.write_text(), p.exists() |
| Syntax | Description |
try: risky_call() except ValueError: handle() | Catch a specific exception type |
except (TypeError, KeyError): | Catch multiple exception types in one block |
except ValueError as e: | Capture the exception object. str(e) for message |
except Exception: | Catch all non-system exceptions. Avoid bare except: |
try: ... except: ... else: no_error() | else runs only if no exception was raised |
try: ... finally: cleanup() | finally always runs, even if exception occurs |
raise ValueError("msg") | Raise an exception explicitly |
raise RuntimeError("new") from e | Chain exceptions. Preserves original traceback |
class MyError(Exception): pass | Define a custom exception class |
assert x > 0, "must be positive" | Debug assertion. Raises AssertionError if condition is False |
| Function | Description |
len(obj) | Length of sequence/collection. len([1,2,3]) → 3 |
range(stop), range(start, stop, step) | Generate integer sequence. list(range(3)) → [0, 1, 2] |
enumerate(iterable, start=0) | Yield (index, value) pairs. list(enumerate("ab")) → [(0,"a"),(1,"b")] |
zip(a, b) | Pair elements from iterables. list(zip([1,2], ["a","b"])) → [(1,"a"),(2,"b")] |
map(fn, iterable) | Apply function to each item. list(map(str, [1,2])) → ["1","2"] |
filter(fn, iterable) | Keep items where fn is truthy. list(filter(None, [0,1,"",2])) → [1,2] |
sorted(iterable, key=fn) | Return sorted list. sorted(["b","a"]) → ["a","b"] |
sorted(lst, key=len, reverse=True) | Sort by custom key, descending |
min(iterable), max(iterable) | Return minimum/maximum. min([3,1,2]) → 1 |
sum(iterable, start=0) | Sum all elements. sum([1,2,3]) → 6 |
any(iterable), all(iterable) | any: True if any truthy. all: True if all truthy |
abs(x), round(x, n) | Absolute value. Round to n decimals |
reversed(seq) | Return reversed iterator. list(reversed([1,2,3])) → [3,2,1] |
isinstance(obj, type) | Type check. isinstance("hi", str) → True |
hasattr(obj, "attr") | Check if object has attribute |
dir(obj) | List all attributes/methods of an object |
help(obj) | Display documentation for an object or function |
| Syntax | Description |
[x**2 for x in range(5)] | List comprehension. → [0, 1, 4, 9, 16] |
[x for x in lst if x > 0] | Filtered list comprehension. Keep only positive values |
[x if x > 0 else 0 for x in lst] | Conditional expression in comprehension (if-else) |
[(x, y) for x in a for y in b] | Nested comprehension. Cartesian product of a and b |
[row[i] for row in matrix] | Extract column i from a 2D list |
{k: v for k, v in pairs} | Dict comprehension. {x: x**2 for x in range(4)} |
{k: v for k, v in d.items() if v > 0} | Filtered dict comprehension |
{x**2 for x in range(5)} | Set comprehension. → {0, 1, 4, 9, 16} |
(x**2 for x in range(5)) | Generator expression (lazy). Use for large datasets to save memory |
sum(x**2 for x in range(5)) | Generator expression inside function call. No extra parentheses needed |
| Syntax | Description |
class Dog: def __init__(self, name): self.name = name | Define a class. __init__ is the constructor |
d = Dog("Rex") | Create an instance. Calls __init__ automatically |
def bark(self): return "Woof!" | Instance method. First param is always self |
class Puppy(Dog): | Inheritance. Puppy inherits all methods from Dog |
super().__init__(name) | Call parent class method. Used in overridden __init__ |
class C(A, B): | Multiple inheritance. MRO (Method Resolution Order) applies |
@property def name(self): return self._name | Property decorator. Access like attribute: obj.name |
@name.setter def name(self, val): self._name = val | Property setter. obj.name = "new" calls this method |
@classmethod def create(cls, data): | Class method. Receives class as first arg. Often used as factory |
@staticmethod def helper(): | Static method. No self or cls. Utility function on the class |
def __str__(self): | String representation for print() and str() |
def __repr__(self): | Debug representation. Used in REPL and repr() |
def __len__(self): | Dunder method for len(obj). Also __getitem__, __iter__, etc. |
from dataclasses import dataclass @dataclass class Point: x: float y: float | Dataclass (Python 3.7+). Auto-generates __init__, __repr__, __eq__ |
| Module / Usage | Description |
import os os.path.exists("f.txt") | File system operations. os.listdir(), os.mkdir(), os.getcwd() |
import sys sys.argv | Command-line args list. sys.exit(), sys.path, sys.stdin |
from pathlib import Path Path("dir").glob("*.py") | Object-oriented paths. Path.home(), p.parent, p.stem |
from datetime import datetime datetime.now() | Date/time. timedelta, strftime(), strptime() |
from collections import Counter Counter("abracadabra") | Count elements. → Counter({"a":5, "b":2, ...}) |
from collections import defaultdict dd = defaultdict(list) | Dict with default factory. dd["key"].append(1) auto-creates list |
from collections import namedtuple Point = namedtuple("Point", ["x","y"]) | Lightweight immutable class. p = Point(1, 2); p.x |
from collections import deque dq = deque([1, 2, 3]) | Double-ended queue. O(1) appendleft() and popleft() |
import itertools itertools.chain(a, b) | Chain iterables. Also product, permutations, combinations, groupby |
itertools.islice(it, 5) | Slice an iterator. islice(count(), 3) → [0, 1, 2] |
import re re.findall(r"\d+", text) | Regex. re.search(), re.sub(), re.match(), re.compile() |
import functools @functools.lru_cache | Memoization decorator. Caches function return values |
functools.reduce(fn, iterable) | Left fold. reduce(lambda a,b: a+b, [1,2,3]) → 6 |
import random random.choice(lst) | Random selection. random.randint(1,10), random.shuffle(lst) |
import math math.sqrt(16) | Math functions. math.pi, math.ceil(), math.floor(), math.log() |