The snippet library.
Small, practical examples. Search by task or narrow things down below.
Run your first program
Python: Start with a complete program that prints one line. Follow the run instructions below.
Python✓ Tested
Select the largest values without sorting everything
Python: Use heapq.nlargest when only a small prefix of the ranking is required.
Python✓ Tested
Separate records into two lists
Python: Build two explicit partitions so callers can use both matching and rejected values.
Python✓ Tested
Skip weekends when advancing dates
Python: Walk calendar dates and count only Monday through Friday.
Python✓ Tested
Sort dictionaries by a value
Sort a list of dictionaries by a numeric field, leaving the original list unchanged.
sort✓ Tested
Split a list into fixed-size batches
Python: Slice a sequence at regular offsets; the final batch can be smaller.
Python✓ Tested
Split a string into words
Split text on whitespace, automatically treating repeated spaces, tabs, and line breaks as a single separator.
string✓ Tested
Store a value in a named variable
Python: Give a value a descriptive name and print it.
Python✓ Tested
Take a limited number of iterator values
Python: Use islice to consume only the requested prefix of a potentially unbounded iterator.
Python✓ Tested
Update a running count
Python: Change a variable after its initial value has been assigned.
Python✓ Tested
Validate an entire identifier
Python: Use fullmatch so a regex must consume the complete input.
Python✓ Tested
Visit adjacent pairs
Python: Use itertools.pairwise to process neighboring items without indexing.
Python✓ Tested