How to Efficiently Extract Every Nth Element from a List in Python?

Susan Sarandon
Release: 2024-10-20 11:17:30
Original
121 people have browsed it

How to Efficiently Extract Every Nth Element from a List in Python?

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>
Copy after login

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
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!