
Python code examples
Browse 250 Python code examples across 25 topics, including lists and tuples, dictionaries and sets, strings.
Jump to a topic
Lists and tuples
Dictionaries and sets
Strings
Numbers and statistics
Functions
Iterators
Collections
Dates and calendars
Files and paths
Serialization
Regular expressions
Classes and typing
Errors and testing
Async and concurrency
Algorithms and data
Sequence techniques
- Clear and refill a list without invalidating references
- Require equal lengths when zipping
- Build two independent lists instead of repeating one
- Splice several rows into a sequence
- Validate the shape of a rectangular table
- Sort text without case-sensitive ordering
- Keep tied records in their original order
- Replace every other list item
- Use a named slice to crop a sequence
- Take the first matching item with a fallback
Dictionary tooling
- Preallocate independent mapping values
- Build a map from paired columns and reject missing values
- Expose a read-only mapping view
- Select and rename record fields
- Convert nested defaultdicts to plain dictionaries
- Serialize a deterministic set union
- Read the most recently added mapping item
- Find values common to several sets
- Compare the key sets of two records
- Join records using a lookup index
Unicode and formatting
- Normalize accents to a canonical form
- Distinguish letters from combining marks
- Remove duplicate spaces without changing line breaks
- Justify an identifier with a custom fill character
- Create a literal representation with ascii
- Read the last segment without splitting other separators
- Handle strings with different newline styles
- Keep quotation marks in formatted debug output
- Dedent an indented multiline string
- Wrap prose to a fixed width
Numeric precision
- Quantize money with an explicit rounding rule
- Isolate a temporary decimal context
- Split an amount into equal groups and distribute the remainder
- Limit a fraction denominator
- Sum floats with reduced cancellation error
- Round up integer division
- Track the integer width of a binary value
- Compute an integer square root
- Calculate a weighted mean
- Find only valid finite readings
Functional patterns
- Validate a callable accepts keyword arguments with signature
- Build a dispatch table with single dispatch
- Build a bounded cache and inspect its hit count
- Attach a listener to a function result
- Define positional-only and keyword-only arguments
- Forward keyword arguments from a dictionary
- Bind loop values in closures
- Use partialmethod to create a named operation
- Read an attribute lazily with cached_property
- Reduce rows with an explicit starting value
Time and schedules
- Read an ISO week date
- Move to the start of the current ISO week
- Convert Unix time to an aware datetime
- Parse a timestamp with a UTC suffix
- Compare aware datetimes in different offsets
- Measure a duration with a monotonic clock
- Count working days in a date range
- Build a half-open daily interval
- Read a duration in total minutes
- Combine a date with a time
Standard library utilities
- Parse command-line flags without touching sys.argv
- Format a log entry with a logger adapter
- Read a TOML array of tables
- Build a stable name-based UUID
- Create a repeatable random sample
- Format bytes using hexadecimal
- Read integers from packed binary data
- Compare checksums to detect an accidental change
- Inspect a ZIP archive in memory
- Compare versions made of numeric segments
Async workflows
- Run related tasks in a task group
- Catch a timeout around a task
- Use an asynchronous context manager
- Handle task group exceptions by type
- Consume ready tasks with as_completed
- Protect an async critical section with a lock
- Set task-local values with ContextVar
- Resolve a Future from the event loop
- Close an async generator early
- Check whether an async queue is full
Filesystem and SQLite
- Use fallback values for missing CSV columns
- Write tab-delimited rows from dictionaries
- Read only the final lines of a stream
- Swap a staged file into place
- Check if a path is lexically under a directory
- Read multiple suffixes of an archive
- Read SQLite result rows by name
- Roll back a failed SQLite transaction
- Update an existing SQLite row with an upsert
- Run cleanup actions in reverse order
Data structures and algorithms
- Sort tasks by dependency with TopologicalSorter
- Detect a cycle in a dependency graph
- Search a sorted collection for all matching positions
- Merge sorted streams lazily
- Rotate waiting jobs through a round-robin queue
- Insert a sorted priority with insort
- Sort records with missing values last
- Build a histogram with explicit buckets
- Replace the cheapest offer in a fixed-size heap
- Cycle through axis labels