Extract Every Nth Element from a List in Python
When faced with the task of extracting every Nth element from a list, such as selecting every 10th item from a list of integers ranging from 0 to 1000, a straightforward approach may involve using a for loop to iterate through the list and check the modulus of each element's index by N. However, there exists a more efficient and elegant method that can accomplish the same result with a single line of code.
Using Python's slicing syntax, we can extract every Nth element by specifying a step size of N. In the example provided, we can obtain the desired list using the following code:
<code class="python">xs = list(range(165)) result = xs[0::10]</code>
This method is considerably faster than iteratively checking each element's index, as demonstrated by the following time comparison:
$ python -m timeit -s "xs = list(range(1000))" "[x for i, x in enumerate(xs) if i % 10 == 0]" 500 loops, best of 5: 476 usec per loop $ python -m timeit -s "xs = list(range(1000))" "xs[0::10]" 100000 loops, best of 5: 3.32 usec per loop
By utilizing the slicing syntax, we can efficiently extract every Nth element from a list in Python, which is particularly beneficial for large lists where speed is a concern.
The above is the detailed content of How to Efficiently Extract Every Nth Element from a List in Python?. For more information, please follow other related articles on the PHP Chinese website!