Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion toolz/itertoolz.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,12 +328,20 @@ def tail(n, seq):
>>> tail(2, [10, 20, 30, 40, 50])
[40, 50]

``n`` must be non-negative; a negative ``n`` raises ``ValueError`` rather
than silently masking an upstream bug in the caller.

See Also:
drop
take
"""
if n < 0:
raise ValueError("n must be non-negative")
try:
return seq[-n:]
# seq[len(seq) - n:] is correct for 0 <= n <= len(seq); clamp the
# lower bound so n > len(seq) returns the whole sequence instead of
# wrapping to a negative index, and n == 0 returns the empty tail.
return seq[max(len(seq) - n, 0):]
except (TypeError, KeyError):
return tuple(collections.deque(seq, n))

Expand Down
14 changes: 14 additions & 0 deletions toolz/tests/test_itertoolz.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,20 @@ def test_tail():
assert list(tail(3, 'ABCDE')) == list('CDE')
assert list(tail(3, iter('ABCDE'))) == list('CDE')
assert list(tail(2, (3, 2, 1))) == list((2, 1))
# n larger than the sequence returns the whole sequence.
assert list(tail(10, 'ABC')) == list('ABC')
assert list(tail(10, iter('ABC'))) == list('ABC')
# tail(0, seq) is the last zero elements: empty, consistently for any
# iterable. Regression for gh #626: seq[-0:] == seq[0:] wrongly returned
# the whole sequence for sliceable inputs, while the deque fallback
# returned empty, so the two input paths disagreed.
assert list(tail(0, 'ABCDE')) == []
assert list(tail(0, iter('ABCDE'))) == []
assert list(tail(0, (3, 2, 1))) == []
# A negative n is a programming error (a masked upstream bug), so it
# raises rather than silently returning empty, matching nth's contract.
assert raises(ValueError, lambda: tail(-2, 'ABCDE'))
assert raises(ValueError, lambda: tail(-2, iter('ABCDE')))


def test_drop():
Expand Down