The snippet library.
Small, practical examples. Search by task or narrow things down below.
Find values present in exactly one set
Python: Use symmetric difference when either side can contain unmatched values.
Python✓ Tested
Find values shared by two collections
Python: Use set intersection and sort the result for deterministic display.
Python✓ Tested
Find what remains after division
Python: Use the remainder operator to count items left after forming complete groups.
Python✓ Tested
Flatten one level of nested lists
Python: Use a nested comprehension when each input item is itself an iterable.
Python✓ Tested
Generate combinations across two collections
Python: Use product for a Cartesian product; this differs from selecting combinations within one collection.
Python✓ Tested
Group records by a field
Python: Accumulate related values with defaultdict without checking whether each group exists.
Python✓ Tested
Handle an expected child-process failure
Python: Catch CalledProcessError when check=True reports a nonzero exit status.
Python✓ Tested
Handle malformed JSON input
Python: Catch JSONDecodeError without hiding unrelated programming errors.
Python✓ Tested
Handle three possible outcomes
Python: Check high, normal and low values with an ordered conditional chain.
Python✓ Tested
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
Insert a value while preserving sorted order
Python: Use insort on an already sorted list; insertion still shifts later list elements.
Python✓ Tested
Invert a dictionary with unique values
Python: Swap keys and values when the values are hashable and unique.
Python✓ Tested