fluttersmith/py-snippetsGitHub ↗

Every nth item of a list

Take every nth item from a sequence, starting with the nth, using a slice.

Lists#iterationO(n / k) time✓ 3 examples pass on 3.11–3.14

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])
  1. 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).

How it works

  • A slice is [start:stop:step]. Starting at n - 1 makes the first pick the n-th item.
  • Slicing a range returns a range, so the result is wrapped in list().
  • n below 1 raises, rather than producing a confusing empty or reversed list.

Complexity: O(n / k) time and space

Importfrom 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.