Python: how to remove/delete every n-th element from list?

◇◆丶佛笑我妖孽 提交于 2019-12-01 22:32:13

In your first function mylist[0::n] is [1, 3] because 0::n means first element is 0 and other elements are every nth element after first. As Daniel suggested you could use mylist[::n] which means every nth element.

In your second function index is starting with 0 and 0 % 0 is 0, so it doesn't copy first element. It's same for third element (2 % 2 is 0). So all you need to do is new_list = [item for index, item in enumerate(mylist) if (index + 1) % n != 0]

Tip: you may want to use return instead of print() in functions like these.

Let's say you have the list :

a = [1,2,3,4,5,6,7,8,9,10]

If you want every k-th element you can do something like

del a[k-1::k]

Example with k=3

The current list is now [1, 2, 4, 5, 7, 8, 10]

The output is correct, you are removing the the elements with index 0, n, 2n, ... . So 1 and 3 are removed, 2 and 4 are left. So if you want to print the 0, n, 2n, ... element, just write

print(mylist[::n])

your first approach looks good to me - you just have to adapt your start index if you want to drop the elements 1, 1+n, 1+2n, ... (as seems to be the case):

lst = list(range(1, 5))
del lst[1::2]
print(lst)

Another way to do this, would be to generate a new list containing only the elements you need.

newList = [x for i, x in enumerate(myList) if i%n !=0]

If n were 5, this would return a list containing the elements [1,2,3,4,6,7,8,9,11...] The advantage of doing it this way is that you keep your original list which is useful if you're going to reuse the data. However, if you're worried about saving memory, then probably not the best.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!