The snippet library.
Small, practical examples. Search by task or narrow things down below.
Remove and return a dictionary entry
Python: Use pop with a default when a missing entry is an expected condition.
Python✓ Tested
Remove duplicates from a list
Remove repeated hashable values while preserving the order in which they first appeared.
list✓ Tested
Rename a file within a directory
Python: Use Path.rename and inspect the resulting path.
Python✓ Tested
Repeat a fixed number of times
Python: Use a counted loop to print three numbered steps.
Python✓ Tested
Repeat while a condition holds
Python: Count down while a positive number remains, updating the loop variable on each iteration.
Python✓ Tested
Replace one collection element
Python: Update an existing element at a known valid index.
Python✓ Tested
Replace text in a string
Replace every occurrence of a substring and keep the result in a new string. The original string is unchanged.
string✓ Tested
Represent a record with a dataclass
Python: Generate initialization and convert a typed record to a dictionary.
Python✓ Tested
Require two conditions to be true
Python: Combine a lower and an upper bound to check whether a value is in range.
Python✓ Tested
Return a small immutable named record
Python: Use NamedTuple when callers need both tuple behavior and named fields.
Python✓ Tested
Round decimal amounts explicitly
Python: Build Decimal values from strings and choose a rounding rule explicitly.
Python✓ Tested
Run cleanup around a custom context
Python: Use try/finally inside a contextmanager so cleanup runs even on failure.
Python✓ Tested