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:
xs = list(range(1001))
new_list = []
for i, x in enumerate(xs):
if i % 10 == 0:
new_list.append(x)
However, a more concise and efficient approach is available using Python's slicing:
>>> xs = list(range(1001))
>>> new_list = xs[0::10]
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:
$ 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
This optimized approach using slicing offers both simplicity and performance advantages for creating new lists with every Nth item from an original list.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3