
Python splitlines and mixed line endings
See how str.splitlines() recognizes CR, LF, and CRLF, while split('\\n') only separates at LF.
FIELD NOTES
The ideas underneath the implementation.

See how str.splitlines() recognizes CR, LF, and CRLF, while split('\\n') only separates at LF.

Probe the next representable float around a threshold without confusing it with a decimal step or tolerance.

A keyword stored by functools.partial is a default for later calls, not a locked setting.

See why dataclasses.replace() reruns initialization and post-init logic instead of copying derived init=False fields.

Understand layered lookup precedence, assignment, and the live links between ChainMap and its source mappings.

Python's str.isdecimal accepts Unicode decimal characters; combine it with isascii when an identifier requires ASCII digits.

Use the divide ufunc's where mask when a branch must avoid invalid arithmetic.

Python 3.12 raises StatisticsError for a one-value input to statistics.quantiles; Python 3.13 changed that behavior. Check the supported runtime when handling tiny samples.

Use statistics.mode for one most-common value and statistics.multimode when every tied mode matters.

itertools.product returns tuples lazily, but first stores each input iterable in memory. Do not pass an unbounded generator expecting streaming Cartesian products.

Plain sorted() compares filename strings lexicographically. Use a numeric key when a number in the name should control order.

Choose statistics.mean when the input numeric type matters. statistics.fmean always returns a float, including for Fraction input.

Use list.sort when changing the existing list is intended. Use sorted when you need a separate ordered result or want to sort any iterable.

itertools.batched groups an iterable into tuples of size n, but the final tuple may be shorter. Add an explicit check if downstream code requires equal batch sizes.

dict.keys(), values(), and items() return dynamic views. Materialize a list when you need the entries captured at one point in time.

functools.cache keeps its internal mapping coherent across threads, but simultaneous misses may call the wrapped function more than once.

When axis is omitted, numpy.take indexes the flattened array. Pass an axis to select along rows or columns without crossing row boundaries.

For increasing bins, numpy.digitize(right=False) includes the left edge and excludes the right. Toggle right when your interval convention requires the opposite.

NumPy nan_to_num defaults infinities to the largest finite values for the input dtype. Choose posinf and neginf explicitly when that is not the desired policy.

NumPy meshgrid defaults to Cartesian xy indexing, which swaps the first two dimensions. Use indexing="ij" when output axes should follow input coordinate vectors.

numpy.empty returns uninitialized values. Allocate with it only when your code writes every slot before any read; otherwise choose an initialized constructor such as zeros.

In NumPy 2.x, asarray(copy=False) is a strict no-copy contract: it raises when conversion needs new storage. Use copy=None when a copy is acceptable.

Search by a comparable key and insert a whole record without confusing the two inputs.

See how NumPy vectorize infers output types from the first input and how otypes makes that call explicit.

See when element-wise maxima propagate NaNs and when they ignore one missing operand.

Separate rows with any match from the coordinates of every matching element.

Avoid running an expensive default factory on cache hits with an explicit membership check.

Explain a negative signed area and keep paired coordinates aligned when sorting samples.

An empty shape tuple describes zero axes, not zero stored elements. Check size when testing emptiness.

Build a one-step lag and validity mask without treating the last observation as the first predecessor.

Compare repeated values, zero fill and in-place mutation when expanding an array.

Count observed values before using nanpercentile and define an explicit all-missing policy.

Compare whether edge values repeat when extending a sequence with mirrored padding.

Round-trip a binary mask without mistaking padding bits for original values.

See when interpolation uses endpoint values and how to mark outside queries.

Detect integer wraparound in running totals and choose an explicit accumulator type.

Understand why broadcast_to is read-only and make a writable copy for independent channel edits.

Count class labels before stratifying and distinguish a necessary count check from a valid evaluation plan.

Read the outgoing value before appending to a full bounded deque so a rolling total remains aligned.

Compare raising, wrapping and clipping indices before selecting values.

Specify the axis to squeeze when another length-one dimension must remain.

Translate sorted insertion positions to original rows and verify exact matches, including the endpoint.

Keep features and labels aligned when repeating rows or tiling a batch.

Use per-axis padding widths and a validity mask to distinguish padding from real zeros.

Move channels from axis one to the last axis and verify values, not only the output shape.

Check the output shape of one-dimensional matrix multiplication and construct an outer product deliberately.

Use an explicit point count and endpoint policy when constructing a floating-point grid.

Distinguish changes per array index from rates per coordinate on an irregular grid.

Keep adjacent differences aligned with later observations and mark a prepended first value as artificial.

Use array_split for a fixed number of sections and handle empty sections when there are fewer rows.

Use an explicit sentinel when None is a valid dictionary value.

Preserve row alignment when shuffling paired feature and label arrays.

Reduce log values without exponentiating each large input directly.

See why NumPy’s relative tolerance can depend on argument order.

Convert integer data to floating point before in-place true division.

Compare direct squaring with NumPy hypot for large finite components.

Keep a finite reduction when a float16 sum exceeds its representable range.

Inspect the fitted range and later values when a training feature is constant.

Understand when a sigmoid transformation preserves a binary ranking score.

Use the complete class label set when a test split omits a model class.

Inspect class support before interpreting a balanced accuracy score on a test split.

Compare round-to-even with an explicit decimal half-up policy using a small reproducible fixture.

Create a fresh list for each independent call while allowing intentional shared state.

Use stable sorting to order ranked records with different directions and predictable ties.

Avoid losing a small increment before taking a logarithm, with an executable floating-point check.

Compare sequential accumulation with math.fsum on a small reproducible cancellation example.

Choose Counter subtraction or the subtract method according to whether signed differences must survive.

Reorder unique labels and remap inverse indices without breaking reconstruction.

Compare stack and concatenate when joining two feature batches and check the resulting shape.

Assign child seed sequences to workers instead of resetting every worker to the same seed.

Check how overlapping window views respond when their source series changes.

Use an explicit argmax axis and take_along_axis to keep row winners aligned with their scores.

Preserve complete rows when a Boolean condition was computed for individual elements.

Preserve an explicit validity mask when averaging rows with missing observations.

Multiply density by bin width to interpret unequal-width histogram bins.

Handle an empty list of batches while preserving the expected two-dimensional feature contract.

Detect inverted clipping intervals before they silently collapse feature values.

Calculate per-class F1 before comparing equal-class and support-weighted averages.

See how lazy slices share a source iterator and when to materialize one batch before taking the next.

Account for the extra initial state before pairing running totals with input batches.

Distinguish original zeros from replaced nonfinite values and inspect the defaults for infinities.

Convert insertion offsets measured in an original sorted array into positions in the expanded result.

Keep the observed label IDs next to their counts when class IDs are negative or far apart.

Distinguish insufficient sample data from a zero population standard deviation in Python.

Recognize repeated references in a nested list and construct an independent list for each row.

Understand why bracket access creates a group and how get can inspect an absent key without adding it.

Splitting a record stream with itertools.tee does not guarantee bounded storage. Check consumer lag and compute compatible metrics in one pass.

Separate rows with no weight from valid weighted averages without inventing a numeric result.

Detect incomplete signal windows before a mean reduction, and choose an explicit boundary policy.

Detect missing score rows before applying NumPy nanargmax, and keep a validity mask separate from the returned indices.

A one-neighbor fixture scores perfectly by retrieving itself. Exclude the same row while retaining other samples with identical feature values.

An epoch-sized draw can repeat some row IDs and omit others. Check visit counts when the training contract requires every row exactly once.

Bind each loop value when building delayed classification callbacks, then test the callbacks after their builder returns.

A new dictionary can still share nested lists with the original record. Copy the mutable field that a transformation will edit.

Relative tolerance alone is usually unsuitable for a near-zero comparison. Make the acceptable absolute error explicit.

A generator stores iterator state. Create a fresh iterator for each pass, or deliberately cache a small finite source before reusing it.

A searchsorted bin-ID calculation needs an explicit final-edge rule to match NumPy histogram. Validate the score range before adjusting that endpoint.

Concatenating held-out predictions changes the target-mean baseline used by R2. Inspect fold scores and residual sums before treating pooled R2 as mean cross-validation performance.

Advanced-indexed += is not a scatter-sum. Use np.add.at when repeated indices must each contribute to an accumulator.

A ufunc mask leaves skipped output positions unchanged. Make per-group means deterministic with an explicit floating output and missing-value policy.

Audit entity IDs as well as row indices when evaluating on unseen users or devices, and distinguish group fractions from row fractions.

Chronological feature rows can still carry future training labels. Audit target times against the model fit boundary, including the forecast horizon.

A large feature offset can make mean(x*x) - mean(x)**2 report a negative variance. Compare centered reduction with exact evidence and distinguish prior precision loss.

Keep true labels on rows and predictions on columns, then verify precision and recall with an asymmetric six-sample fixture.

For hard binary targets, logaddexp gives a compact per-example loss that avoids explicitly forming saturated probabilities.

Compute recall-weighted precision at distinct score thresholds, keep ties together, and avoid relabeling a trapezoidal PR integral as average precision.

itertools.groupby groups consecutive matching keys. Sort by the same key first when a global label summary is intended.

argpartition selects a boundary efficiently, but tied values can leave membership or order unspecified. Add an explicit key when repeatable top-k output matters.

The in_order option can trade FIFO delivery for earlier completed batches. Understand the reproducibility and class-order risks before enabling it.

NumPy reductions can return a wrapped integer when the accumulator dtype is too small; check the range and choose the accumulator deliberately.

Filesystem iteration order is not guaranteed. Sort a fixed file list before position-based splits, and persist assignments when the dataset changes.

With multi-process loading, each IterableDataset worker gets a dataset replica. Configure each replica to read a distinct shard and check what happens to the tail.

Array comparisons produce elementwise results, so choose any, all, or a separate emptiness check when writing NumPy conditions.

Python's default zip stops at the shortest input. Use strict=True when paired ML data must have matching lengths.

A seed restarts a NumPy generator, but does not freeze its state or promise identical streams across NumPy versions.

A reshaped feature array can alias the original data, while integer-array selection makes a copy. Inspect both before mutating a pipeline intermediate.

A smaller final batch can distort an epoch loss when every batch mean gets equal weight. Use the denominator that matches the loss you mean to report.

A shape-compatible operation can still compare the wrong values. Diagnose a silent pairwise-error bug before it reaches your metrics.

Use a small scaler diagnostic to see whether held-out data is influencing training, then put the boundary inside a scikit-learn pipeline.