[Tutor] reducing a list evenly when deleting elements by index

Steven D'Aprano steve at pearwood.info
Mon Sep 17 05:25:53 CEST 2012

On 17/09/12 11:15, Pete O'Connell wrote:
> Hi, I have a bezier line with 20 points on it and I am trying to reduce
> this to a line with 4 points, keeping the first and last points and 2
> evenly spaced points in between like so:

In general in Python, it is faster and much easier to create a new list
rather than to mess about deleting items from a list.

So instead of calling del 16 times, which has to move list items around,
it will be faster and simpler to create a new list:

new = [old[0], old[6], old[13], old[19]]

then just use the new list. If you really need to modify the old list in
place (perhaps because other parts of the code need to see the same
change) then you can do a slice-assignment:

old[:] = new  # note the [:] slice


More information about the Tutor mailing list