Python Standard Library Highlights
Table of Contents
1. Built-in Functions
# Essential built-ins
len([1, 2, 3]) # 3
sum([1, 2, 3]) # 6
min([3, 1, 4]) # 1
max([3, 1, 4]) # 4
sorted([3, 1, 4]) # [1, 3, 4]
reversed([1, 2, 3]) # iterator: 3, 2, 1
enumerate(['a', 'b', 'c']) # (0,'a'), (1,'b'), (2,'c')
zip([1, 2], ['a', 'b']) # (1,'a'), (2,'b')
map(str, [1, 2, 3]) # ['1', '2', '3']
filter(bool, [0, 1, '', 'a']) # [1, 'a']
any([False, True, False]) # True
all([True, True, False]) # False
2. collections
from collections import defaultdict, Counter, deque, namedtuple
# defaultdict - dict with default factory
word_count = defaultdict(int)
for word in words:
word_count[word] += 1
# Counter - count hashable objects
Counter(['a', 'b', 'a', 'c', 'a']) # Counter({'a': 3, 'b': 1, 'c': 1})
Counter("hello").most_common(2) # [('l', 2), ('h', 1)]
# deque - double-ended queue
d = deque([1, 2, 3], maxlen=5)
d.appendleft(0) # [0, 1, 2, 3]
d.pop() # 3
# namedtuple - lightweight class
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
p.x, p.y # 3, 4
3. functools
from functools import lru_cache, partial, reduce
# lru_cache - memoization
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
# partial - fix function arguments
from operator import mul
double = partial(mul, 2)
double(5) # 10
# reduce - fold a sequence
reduce(lambda x, y: x + y, [1, 2, 3, 4]) # 10
4. pathlib
from pathlib import Path
# Path operations
p = Path("/home/user/documents")
p / "file.txt" # /home/user/documents/file.txt
p.exists() # True/False
p.is_dir() # True
p.parent # /home/user
p.name # documents
p.suffix # '' (no extension)
# File operations
Path("file.txt").read_text()
Path("file.txt").write_text("content")
list(Path(".").glob("*.py")) # all Python files
5. json
import json
# Serialize
data = {"name": "Alice", "age": 30}
json_str = json.dumps(data, indent=2)
Path("data.json").write_text(json_str)
# Deserialize
loaded = json.loads(json_str)
data = json.loads(Path("data.json").read_text())
6. typing
from typing import Optional, List, Dict, Callable, TypeVar
def greet(name: str) -> str:
return f"Hello, {name}"
def process(items: List[int]) -> Dict[str, int]:
return {"sum": sum(items), "count": len(items)}
def maybe_int(value: str) -> Optional[int]:
try:
return int(value)
except ValueError:
return None
# Generic types
T = TypeVar('T')
def first(items: List[T]) -> Optional[T]:
return items[0] if items else None