int | Integer numbers: 42, -17, 0 |
float | Decimal numbers: 3.14, -0.5 |
str | Text strings: "hello", 'world' |
bool | Boolean: True, False |
list | Ordered mutable sequence: [1, 2, 3] |
tuple | Ordered immutable sequence: (1, 2, 3) |
dict | Key-value pairs: {"a": 1, "b": 2} |
set | Unique unordered items: {1, 2, 3} |
None | Null/empty value |
+ - * / | Arithmetic operators |
// | Integer division |
% | Modulo (remainder) |
** | Exponentiation |
== != < > <= >= | Comparison operators |
and or not | Logical operators |
in / not in | Membership operators |
is / is not | Identity operators |
s.upper() | Convert to uppercase |
s.lower() | Convert to lowercase |
s.strip() | Remove leading/trailing whitespace |
s.split(sep) | Split string into list |
s.join(list) | Join list into string |
s.replace(old, new) | Replace substring |
s.find(sub) | Find substring index (-1 if not found) |
s.startswith(pre) | Check if starts with prefix |
s.endswith(suf) | Check if ends with suffix |
f"Hello {name}" | F-string (recommended) |
f"{value:.2f}" | Format float to 2 decimals |
f"{num:05d}" | Zero-pad number to 5 digits |
"{} {}".format(a, b) | Format method |
"%s %d" % (s, n) | Old-style formatting |
list.append(x) | Add item to end |
list.extend(iter) | Add all items from iterable |
list.insert(i, x) | Insert item at index |
list.remove(x) | Remove first occurrence of x |
list.pop(i) | Remove and return item at index |
list.sort() | Sort list in place |
list.reverse() | Reverse list in place |
list.index(x) | Find index of first occurrence |
list.count(x) | Count occurrences of x |
list[start:end:step] | Slice list |
d.keys() | Get all keys |
d.values() | Get all values |
d.items() | Get all key-value pairs |
d.get(key, default) | Get value with default |
d.pop(key) | Remove and return value |
d.update(dict2) | Merge another dictionary |
d.setdefault(key, val) | Set if key missing |
key in d | Check if key exists |
d | d2 | Merge dicts (3.9+) |
s.add(x) | Add element |
s.remove(x) | Remove element (error if missing) |
s.discard(x) | Remove element (no error) |
s1 | s2 | Union |
s1 & s2 | Intersection |
s1 - s2 | Difference |
s1 ^ s2 | Symmetric difference |
if condition: | If statement |
elif condition: | Else if |
else: | Else |
x if cond else y | Ternary expression |
match value: case x: | Pattern matching (3.10+) |
for x in iterable: | For loop |
for i, x in enumerate(iter): | Loop with index |
for k, v in dict.items(): | Loop dict key-value |
while condition: | While loop |
break | Exit loop immediately |
continue | Skip to next iteration |
else: | Execute if no break |
pass | Do nothing (placeholder) |
def func(args): | Define function |
return value | Return value from function |
def func(a, b=1): | Default argument |
*args | Variable positional arguments |
**kwargs | Variable keyword arguments |
lambda x: x * 2 | Anonymous function |
@decorator | Function decorator |
def func(x: int) -> str: | Type hints |
len(x) | Get length of sequence |
range(start, stop, step) | Generate number sequence |
enumerate(iter) | Get index and value pairs |
zip(iter1, iter2) | Pair items from iterables |
map(func, iter) | Apply function to all items |
filter(func, iter) | Filter items by function |
sorted(iter, key=f) | Return sorted list |
reversed(iter) | Return reversed iterator |
sum(iter) | Sum all numbers |
min(iter) / max(iter) | Get minimum/maximum |
any(iter) / all(iter) | Check if any/all true |
isinstance(obj, type) | Check object type |
type(obj) | Get object type |
print(*args, sep, end) | Output to console |
input(prompt) | Read user input |
[x for x in iter] | List comprehension |
[x for x in iter if cond] | List with condition |
[f(x) for x in iter] | List with transformation |
{x for x in iter} | Set comprehension |
{k: v for k, v in iter} | Dict comprehension |
(x for x in iter) | Generator expression |
open(f, "r") | Open for reading |
open(f, "w") | Open for writing (overwrite) |
open(f, "a") | Open for appending |
open(f, "rb") | Open binary for reading |
with open(f) as file: | Context manager (auto-close) |
file.read() | Read entire file |
file.readline() | Read one line |
file.readlines() | Read all lines as list |
file.write(s) | Write string to file |
file.writelines(list) | Write list of strings |
try: / except: | Catch exceptions |
except Error as e: | Catch specific exception |
except (E1, E2): | Catch multiple exceptions |
else: | Execute if no exception |
finally: | Always execute (cleanup) |
raise Exception(msg) | Raise exception |
raise from e | Chain exceptions |
assert condition | Assert condition is true |
class MyClass: | Define a class |
class Child(Parent): | Inheritance |
class C(A, B): | Multiple inheritance |
def __init__(self): | Constructor |
def __str__(self): | String representation |
def __repr__(self): | Debug representation |
def __len__(self): | Length protocol |
def __eq__(self, other): | Equality comparison |
def __lt__(self, other): | Less than comparison |
def __hash__(self): | Hash for dict keys |
def __getitem__(self, key): | Enable [] indexing |
def __setitem__(self, key, val): | Enable [] assignment |
def __iter__(self): | Make iterable |
def __next__(self): | Iterator protocol |
def __call__(self): | Make callable |
def __enter__(self): | Context manager enter |
def __exit__(self, *args): | Context manager exit |
@property | Getter property |
@name.setter | Setter property |
@classmethod | Class method (cls) |
@staticmethod | Static method |
@dataclass | Auto-generate methods |
@dataclass(frozen=True) | Immutable dataclass |
field(default_factory=list) | Mutable default |
class Proto(Protocol): | Structural typing |
ABC / abstractmethod | Abstract base class |
@decorator | Apply decorator |
@decorator(arg) | Decorator with args |
@dec1 @dec2 | Stack decorators |
@functools.wraps(func) | Preserve function metadata |
@functools.lru_cache | Memoize function |
@functools.cached_property | Cached property |
@contextlib.contextmanager | Create context manager |
# Simple decorator
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"Took {time.time() - start:.2f}s")
return result
return wrapper
# Decorator with arguments
def repeat(times):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello {name}") os.getcwd() | Current working directory |
os.listdir(path) | List directory contents |
os.makedirs(path) | Create directories |
os.path.join(a, b) | Join paths |
os.path.exists(path) | Check if path exists |
os.environ["KEY"] | Environment variables |
sys.argv | Command line arguments |
sys.exit(code) | Exit program |
sys.path | Module search paths |
Path("file.txt") | Create path object |
Path.cwd() / Path.home() | Current/home directory |
p.exists() / p.is_file() | Check existence/type |
p.read_text() / p.write_text() | Read/write text |
p.mkdir(parents=True) | Create directories |
p.glob("*.py") | Pattern matching |
p.stem / p.suffix | Filename / extension |
p.parent / p.name | Parent dir / filename |
json.dumps(obj) | Object to JSON string |
json.loads(s) | JSON string to object |
json.dump(obj, file) | Write JSON to file |
json.load(file) | Read JSON from file |
datetime.now() | Current datetime |
datetime.strptime(s, fmt) | Parse datetime string |
dt.strftime(fmt) | Format datetime |
timedelta(days=1) | Time duration |
re.search(pattern, s) | Find first match |
re.match(pattern, s) | Match at start |
re.findall(pattern, s) | Find all matches |
re.sub(pattern, repl, s) | Replace matches |
re.split(pattern, s) | Split by pattern |
re.compile(pattern) | Compile pattern |
m.group() / m.groups() | Get match/groups |
r"\d+" (raw string) | Raw string for regex |
async def func(): | Define async function |
await coro | Wait for coroutine |
asyncio.run(main()) | Run async entry point |
asyncio.sleep(secs) | Async sleep |
asyncio.create_task(coro) | Schedule coroutine |
asyncio.gather(*coros) | Run concurrently |
asyncio.wait_for(coro, timeout) | Wait with timeout |
async for item in async_iter: | Async iteration |
async with resource: | Async context manager |
import asyncio
async def fetch_data(url):
await asyncio.sleep(1) # Simulate network
return f"Data from {url}"
async def main():
# Run tasks concurrently
tasks = [
fetch_data("url1"),
fetch_data("url2"),
fetch_data("url3"),
]
results = await asyncio.gather(*tasks)
for r in results:
print(r)
asyncio.run(main()) # List comprehension with condition
evens = [x for x in range(10) if x % 2 == 0]
# Dictionary from two lists
d = dict(zip(keys, values))
# Read file lines
with open("file.txt") as f:
lines = f.readlines()
# Lambda with map
doubled = list(map(lambda x: x * 2, numbers))
# Ternary expression
result = "yes" if condition else "no"
# Unpack values
a, b, *rest = [1, 2, 3, 4, 5]
# Walrus operator (3.8+)
if (n := len(data)) > 10:
print(f"Got {n} items")
# Context manager for multiple files
with open("in.txt") as f1, open("out.txt", "w") as f2:
f2.write(f1.read()) python -m venv env to create virtual environmentspip freeze > requirements.txt to save dependenciesif __name__ == "__main__": for script entry points