How to Generate a New List with Every Nth Item from an Original List?

Mary-Kate Olsen
Release: 2024-10-20 10:56:02
Original
658 people have browsed it

How to Generate a New List with Every Nth Item from an Original List?

Create a List with Every Nth Item from an Original List

In data analysis or programming, it's often necessary to work with a subset of a list. One common task is to create a new list containing only every Nth item from the original list. For instance, given a list of integers from 0 to 1000, how can we obtain a list that includes only the first and every subsequent 10th item?

Using a traditional for loop, we can accomplish this task as follows:

<code class="python">xs = list(range(1001))
new_list = []
for i, x in enumerate(xs):
    if i % 10 == 0:
        new_list.append(x)</code>
Copy after login

However, a more concise and efficient approach is available using Python's slicing:

<code class="python">>>> xs = list(range(1001))
>>> new_list = xs[0::10]</code>
Copy after login

In this solution, the xs[0::10] expression creates a new list that includes every 10th item starting from index 0. The result is a list containing [0, 10, 20, 30, ..., 1000] without the need for looping or conditional checks.

This method is significantly faster than the for loop approach, proving advantageous when dealing with large lists. As demonstrated by the following timing comparison:

<code class="python">$ 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</code>
Copy after login

This optimized approach using slicing offers both simplicity and performance advantages for creating new lists with every Nth item from an original list.

The above is the detailed content of How to Generate a New List with Every Nth Item from an Original List?. 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!