pysnippets.lists.every_nth
Every nth item of a list
every_nth(items: Sequence[T], n: int) -> list[T]
Take every nth item from a sequence, starting with the nth, using a slice.
Thin a dataset, pick every third row, sample a log: it’s one slice once you know the start and step.
every_nth.py✓ ruff · mypy --strict
from collections.abc import Sequence
from typing import TypeVar
T = TypeVar("T")
def every_nth(items: Sequence[T], n: int) -> list[T]:
"""Return every ``n``-th item of ``items``, starting with the ``n``-th."""
if n < 1:
raise ValueError(f"n must be at least 1, got {n}")
return list(items[n - 1 :: n])- start at index n - 1, step n
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> every_nth([1, 2, 3, 4, 5, 6], 2)[2, 4, 6]passed on Python 3.11 to 3.14: >>> every_nth(range(1, 11), 3)[3, 6, 9]passed on Python 3.11 to 3.14: >>> every_nth([1, 2], 5)[]Edit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).
python 3.14 · in your browser
Loading Python 3.14 in your browser (≈7 MB, cached after the first time)…
Tab inserts four spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the examples.
How it works
- A slice is
[start:stop:step]. Starting atn - 1makes the first pick the n-th item. - Slicing a
rangereturns arange, so the result is wrapped inlist(). nbelow 1 raises, rather than producing a confusing empty or reversed list.
Complexity: O(n / k) time and space
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from pysnippets.lists.every_nth import every_nthNo dependencies: copy every_nth.py into your project, or clone the repo.Adapted from every-nth in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Typed, validates n, works on any sequence. Suggest an edit.