Skip to content
Advertisement

Index all *except* one item in python

Is there a simple way to index all elements of a list (or array, or whatever) except for a particular index? E.g.,

  • mylist[3] will return the item in position 3

  • milist[~3] will return the whole list except for 3

Advertisement

Answer

For a list, you could use a list comp. For example, to make b a copy of a without the 3rd element:

JavaScript

This is very general, and can be used with all iterables, including numpy arrays. If you replace [] with (), b will be an iterator instead of a list.

Or you could do this in-place with pop:

JavaScript

In numpy you could do this with a boolean indexing:

JavaScript

which will, in general, be much faster than the list comprehension listed above.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement