Home >Backend Development >Python Tutorial >How to Extract Every Nth Item from a List in Python Efficiently?
Extracting Every Nth Item from a List
A common task in programming is to create a new list containing only specific elements from an existing list. One such scenario is selecting every Nth item from the original sequence.
Consider an integer list from 0 to 1000:
[0, 1, 2, 3, ..., 997, 998, 999]
The goal is to obtain a new list that includes the first and every subsequent 10th item:
[0, 10, 20, 30, ..., 990]
While a for loop with modulus checking can accomplish this task, a more concise and efficient approach exists. Python provides a convenient slicing method that allows for straightforward element selection.
The following single-line code snippet leverages Python's slicing mechanism to extract every 10th item:
<code class="python">xs[0::10]</code>
Here, xs represents the original list. The slice syntax [start:stop:step] instructs Python to extract elements from index start to index stop, incrementing by step with each iteration. In this case, we start at index 0 and increment by 10, resulting in:
[0, 10, 20, 30, ..., 990]
Compared to a traditional for loop implementation, this slicing approach is significantly faster. Benchmarking using the timeit module reveals that slicing performs approximately 100 times faster than iterating and applying a modulus check.
In Python, slicing provides a powerful and concise mechanism for extracting and manipulating list elements. It allows for efficient and elegant solutions to common programming tasks, such as selecting every Nth item from a sequence.
The above is the detailed content of How to Extract Every Nth Item from a List in Python Efficiently?. For more information, please follow other related articles on the PHP Chinese website!