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

Find values present in exactly one set

Python: Use symmetric difference when either side can contain unmatched values.

Python✓ Tested
PythonMappings & sets

Find values shared by two collections

Python: Use set intersection and sort the result for deterministic display.

Python✓ Tested
PythonGetting Started

Find what remains after division

Python: Use the remainder operator to count items left after forming complete groups.

Python✓ Tested
PythonIteration & sequences

Flatten one level of nested lists

Python: Use a nested comprehension when each input item is itself an iterable.

Python✓ Tested
PythonIteration & sequences

Generate combinations across two collections

Python: Use product for a Cartesian product; this differs from selecting combinations within one collection.

Python✓ Tested
PythonMappings & sets

Group records by a field

Python: Accumulate related values with defaultdict without checking whether each group exists.

Python✓ Tested
PythonFunctions & error handling

Handle an expected child-process failure

Python: Catch CalledProcessError when check=True reports a nonzero exit status.

Python✓ Tested
PythonStructured data & serialization

Handle malformed JSON input

Python: Catch JSONDecodeError without hiding unrelated programming errors.

Python✓ Tested
PythonGetting Started

Handle three possible outcomes

Python: Check high, normal and low values with an ordered conditional chain.

Python✓ Tested
PythonFile operations & archives

Hash a file without reading it all at once

Python: Feed fixed-size binary chunks into SHA-256 for files larger than memory.

Python✓ Tested
PythonNumbers & calculations

Insert a value while preserving sorted order

Python: Use insort on an already sorted list; insertion still shifts later list elements.

Python✓ Tested
PythonMappings & sets

Invert a dictionary with unique values

Python: Swap keys and values when the values are hashable and unique.

Python✓ Tested