Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

How to remove every N‑th element from a list in Python

1 Answer

0 votes
# ------------------------------------------------------------
# A small program demonstrating how to remove every Nth element
# from a list using clear, expressive Python patterns.
# ------------------------------------------------------------

from typing import List, Any


def remove_every_nth(items: List[Any], n: int) -> List[Any]:
    """
    Return a new list with every n-th element removed.

    The function uses enumerate to pair each element with its index.
    Because enumerate starts at 0, we check (index + 1) % n == 0
    to identify positions that should be removed.

    List comprehensions provide a concise and efficient way to build
    the filtered list without mutating the original.
    """
    if n <= 0:
        raise ValueError("n must be a positive integer")

    return [
        item
        for index, item in enumerate(items)
        if (index + 1) % n != 0
    ]


def main() -> None:
    """
    Demonstrate the function with a simple example.
    Keeping main small and focused makes the program easy to extend.
    """
    data = list(range(1, 21))  # Example list: numbers 1–20
    n = 3                      # Remove every 3rd element

    cleaned = remove_every_nth(data, n)

    print("Original:", data)
    print(f"After removing every {n}rd element:", cleaned)


if __name__ == "__main__":
    main()


# run:
#
# Original: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
# After removing every 3rd element: [1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20]
#

 



answered Aug 15 by avibootz
...