Chichi - 9 months ago 88

Python Question

I had already looked through this post:

Python: building new list from existing by dropping every n-th element, but for some reason it does not work for me:

I tried this way:

`def drop(mylist, n):`

del mylist[0::n]

print(mylist)

This function takes a list and

`n`

Here is my function call:

`drop([1,2,3,4],2)`

Wrong output:

`[2, 4]`

`[1, 3]`

Then I tried a variant from the link above:

`def drop(mylist, n):`

new_list = [item for index, item in enumerate(mylist) if index % n != 0]

print(new_list)

Again, function call:

`drop([1,2,3,4],2)`

Gives me the same wrong result:

`[2, 4]`

`[1, 3]`

How to correctly remove

Answer

In your first function `mylist[0::n]`

is `[1, 3]`

because `0::n`

means first element is 0 and other elements are every n*th* element after first. As Daniel suggested you could use `mylist[::n]`

which means every n*th* 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.

Source (Stackoverflow)