Indexing with List of Indices to Exclude

indexing, list, python

Solution

>>> to_exclude = {1, 2}
>>> vector = ['a', 'b', 'c', 'd']
>>> vector2 = [element for i, element in enumerate(vector) if i not in to_exclude]

The tricks here are:

- Use a list comprehension to transform one list into another. (You can also use the `filter` function, especially if the predicate you're filtering on is already lying around as a function with a nice name.)

- Use `enumerate` to get each element and its index together.

- Use the `in` operator against any `Set` or `Sequence`* type to decide which ones to filter. (A `set` is most efficient if there are a lot of values, and probably conceptually the right answer… But it really doesn't matter much for just a handful; if you've already got a list or tuple with 4 indices in it, that's a "`Set` or `Sequence`" too, so you can just use it.)

* Technically, any `Container` will do. But most `Container`s that aren't a `Set` or `Sequence` would be silly here.

Problem

This is similar to some other questions (Explicitly select items from a Python list or tuple, Grabbing specific indices of a list in Python), but I'm looking to do the opposite: What is a clean way to specify a list/tuple of indices to exclude, instead of to select? I'm thinking of something similar to R or MATLAB where you can specify indices to exclude, like: ``` vector1 <- c('a', 'b', 'c', 'd') vector2 <- vector1[-1] # ['b', 'c', 'd'] vector3 <- vector1[c(-1, -2)] # ['c', 'd'] ``` Is there a good way to accomplish the same thing in Python? Apologizes if this is a dupe, I wasn't sure exactly what to search for.

Original source

Related problems