Skip to content

fix: tail(0, seq) should return empty instead of the whole sequence#629

Open
kaizeenn wants to merge 1 commit into
pytoolz:masterfrom
kaizeenn:master
Open

fix: tail(0, seq) should return empty instead of the whole sequence#629
kaizeenn wants to merge 1 commit into
pytoolz:masterfrom
kaizeenn:master

Conversation

@kaizeenn

@kaizeenn kaizeenn commented Jul 4, 2026

Copy link
Copy Markdown

Summary

Fixes #626.

tail(0, seq) returns the whole sequence for sliceable inputs and empty for iterables — inconsistent and wrong.

Root cause

tail(n, seq) is implemented as seq[-n:]. When n == 0, seq[-0:] is seq[0:], returning the entire sequence. Non-sliceable iterables use deque(seq, 0) which correctly returns empty, making the behavior inconsistent across input types.

tail(0, [10, 20, 30])        # [10, 20, 30]   (wrong)
tuple(tail(0, iter([10, 20, 30])))   # ()      (correct)

Fix

Handle n == 0 as a special case before the main logic:

  • For sliceable types: return seq[:0] (empty of the same type)
  • For non-sliceable iterables: return () (empty tuple, consistent with deque fallback)

Test evidence

$ python3 -m pytest toolz/tests/test_itertoolz.py -v --tb=short
...
50 passed in 0.14s

$ python3 -m pytest toolz/tests/
...
180 passed, 1 failed in 0.49s

(The only failure is test_has_version which requires the package to be installed.)

`tail(0, seq)` is implemented as `seq[-n:]` which for `n == 0` becomes
`seq[-0:]` = `seq[0:]` — returning the entire sequence instead of
the last zero elements. This also makes `tail` inconsistent across
iterable types: sliceable inputs return the whole sequence, while
non-sliceable iterables hit the `deque(seq, 0)` fallback and
correctly return empty.

Fix by handling `n == 0` as a special case, returning `seq[:0]` for
sliceable types and `()` for non-sliceable iterables.

Fixes pytoolz#626.

Signed-off-by: kaizeenn <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

tail(0, seq) returns the whole sequence instead of empty (and is inconsistent across iterable types)

1 participant