Python code snippets with use cases
22 ready-made code building blocks, sorted by topic.
Basics
- Hello World β A first test that the environment works.
- Variables and types β Store values and check their type.
- Date and time β Calculate deadlines, format timestamps.
Data structures
- Working with lists β Manage collections of values: add, sort, filter.
- Dictionary β Store mappings, e.g. configurations or JSON-like data.
- Sorting by a custom key β Order records by a field, e.g. users by age.
Advanced
- Generator β Process large amounts of data piece by piece without holding everything in memory.
- Decorator for timing β Add runtime measurement, logging or caching uniformly to many functions.
- Custom context manager β Reliably open and close resources (timers, connections, locks).
- Running tasks in parallel with ThreadPool β Handle many slow I/O tasks (downloads, API calls) at the same time.
More snippets
- if / elif / else β React differently, e.g. calculate grades or price tiers.
- for loop β Process every element of a list or repeat n times.
- Function with default value β Bundle recurring logic, e.g. greeting texts or calculations.
- Class with inheritance β Bundle data and behavior, e.g. users, products, game characters.
- Dataclass β Pure data objects without boilerplate, e.g. configurations or DTOs.
- try / except / finally β Guard user input or network access without the program crashing.
- Reading and writing a file β Save and load logs, configurations or text data.
- Reading and writing JSON β Exchange data with web APIs or other programs.
- Counting words β Text analysis, e.g. most frequent words in a document.
- Regular expression β Find email addresses, phone numbers or patterns in text.
- HTTP request (requests) β Fetch data from a web API.
- Command-line arguments β Build your own CLI tools with options.