Python

Variables & Types

x = 10Assign variable (dynamic typing)
type(x)Get type of variable
int / float / str / boolPrimitive types
int("42")Type casting to integer
isinstance(x, int)Type check
NoneNull value equivalent
x, y = 1, 2Multiple assignment
f"Hello {name}"F-string interpolation

String Methods

.strip()Remove leading/trailing whitespace
.split(sep)Split into list
.join(list)Join list into string
.replace(old, new)Replace substring
.find(sub)Index of substring (-1 if not found)
.startswith() / .endswith()Check prefix/suffix
.upper() / .lower()Case conversion
.format()String formatting
.isdigit()Check if all digits
len(s)String length

Lists

lst = [1, 2, 3]Create a list
lst[0] / lst[-1]Index from start/end
lst[1:3]Slice (index 1 to 2)
.append(x)Add to end
.extend(lst2)Add all items from another list
.insert(i, x)Insert at index
.pop(i)Remove & return at index
.remove(x)Remove first occurrence
.sort() / sorted()Sort in-place / new list
.reverse()Reverse in-place
[x for x in lst if cond]List comprehension
len(lst)Number of elements

Dictionaries

d = {"k": "v"}Create dictionary
d["key"]Access value (KeyError if missing)
d.get("key", default)Safe access with default
d.keys() / d.values()View keys / values
d.items()Key-value pairs
d.update(d2)Merge another dict
d.pop("key")Remove and return value
"key" in dCheck if key exists
{k: v for k, v in ...}Dict comprehension
d | d2Merge dicts (3.9+)

Control Flow

if / elif / elseConditional branching
for x in iterable:For loop
while condition:While loop
for i in range(n):Loop n times
for i, v in enumerate(lst):Loop with index
for k, v in d.items():Loop over dict
break / continueExit or skip iteration
x if cond else yTernary expression
match val: case ...Pattern matching (3.10+)

Functions

def fn(a, b):Define function
def fn(a, b=5):Default argument
def fn(*args):Variable positional args
def fn(**kwargs):Variable keyword args
return valueReturn from function
lambda x: x * 2Anonymous function
def fn() -> int:Return type hint
@decoratorFunction decorator
yield valueGenerator function

Classes & OOP

class MyClass:Define a class
def __init__(self):Constructor method
self.attr = valInstance attribute
class B(A):Inheritance
super().__init__()Call parent constructor
@staticmethodNo self/cls reference
@classmethodTakes cls as first arg
@propertyGetter decorator
__str__ / __repr__String representation
__len__ / __getitem__Dunder methods for len/indexing

Error Handling

try: / except:Catch exceptions
except ValueError as e:Catch specific error
finally:Always executes
raise Exception(msg)Raise an error
assert cond, msgAssert condition
with open() as f:Context manager

Common Built-ins

print()Output to console
input()Read user input
range(n)Sequence 0 to n-1
len()Length of collection
max() / min()Largest / smallest
sum()Sum of iterable
abs()Absolute value
round()Round number
zip(a, b)Pair up iterables
map(fn, lst)Apply fn to each
filter(fn, lst)Keep matching items
any() / all()Test iterable booleans

File & Modules

import moduleImport entire module
from mod import funcImport specific name
open("f.txt", "r")Open file for reading
f.read() / f.readlines()Read file content
f.write(data)Write to file
import jsonJSON parsing module
json.loads(s) / json.dumps(o)Parse / serialize JSON
os.path.join()Join file paths safely
allprintabledoc.com