FIND YOUR NEXT FEW LINES

The snippet library.

Small, practical examples. Search by task or narrow things down below.

125 snippets foundClear filters
PythonMappings & sets

Remove and return a dictionary entry

Python: Use pop with a default when a missing entry is an expected condition.

Python✓ Tested
PythonCollections

Remove duplicates from a list

Remove repeated hashable values while preserving the order in which they first appeared.

list✓ Tested
PythonFile operations & archives

Rename a file within a directory

Python: Use Path.rename and inspect the resulting path.

Python✓ Tested
PythonGetting Started

Repeat a fixed number of times

Python: Use a counted loop to print three numbered steps.

Python✓ Tested
PythonGetting Started

Repeat while a condition holds

Python: Count down while a positive number remains, updating the loop variable on each iteration.

Python✓ Tested
PythonGetting Started

Replace one collection element

Python: Update an existing element at a known valid index.

Python✓ Tested
PythonStrings & dates

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
PythonStructured data & serialization

Represent a record with a dataclass

Python: Generate initialization and convert a typed record to a dictionary.

Python✓ Tested
PythonGetting Started

Require two conditions to be true

Python: Combine a lower and an upper bound to check whether a value is in range.

Python✓ Tested
PythonStructured data & serialization

Return a small immutable named record

Python: Use NamedTuple when callers need both tuple behavior and named fields.

Python✓ Tested
PythonNumbers & calculations

Round decimal amounts explicitly

Python: Build Decimal values from strings and choose a rounding rule explicitly.

Python✓ Tested
PythonFunctions & error handling

Run cleanup around a custom context

Python: Use try/finally inside a contextmanager so cleanup runs even on failure.

Python✓ Tested