FIND YOUR NEXT FEW LINES

The snippet library.

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

125 snippets foundClear filters
PythonGetting Started

Run your first program

Python: Start with a complete program that prints one line. Follow the run instructions below.

Python✓ Tested
PythonNumbers & calculations

Select the largest values without sorting everything

Python: Use heapq.nlargest when only a small prefix of the ranking is required.

Python✓ Tested
PythonIteration & sequences

Separate records into two lists

Python: Build two explicit partitions so callers can use both matching and rejected values.

Python✓ Tested
PythonDates & time zones

Skip weekends when advancing dates

Python: Walk calendar dates and count only Monday through Friday.

Python✓ Tested
PythonCollections

Sort dictionaries by a value

Sort a list of dictionaries by a numeric field, leaving the original list unchanged.

sort✓ Tested
PythonIteration & sequences

Split a list into fixed-size batches

Python: Slice a sequence at regular offsets; the final batch can be smaller.

Python✓ Tested
PythonStrings & dates

Split a string into words

Split text on whitespace, automatically treating repeated spaces, tabs, and line breaks as a single separator.

string✓ Tested
PythonGetting Started

Store a value in a named variable

Python: Give a value a descriptive name and print it.

Python✓ Tested
PythonIteration & sequences

Take a limited number of iterator values

Python: Use islice to consume only the requested prefix of a potentially unbounded iterator.

Python✓ Tested
PythonGetting Started

Update a running count

Python: Change a variable after its initial value has been assigned.

Python✓ Tested
PythonText validation & encoding

Validate an entire identifier

Python: Use fullmatch so a regex must consume the complete input.

Python✓ Tested
PythonIteration & sequences

Visit adjacent pairs

Python: Use itertools.pairwise to process neighboring items without indexing.

Python✓ Tested