Index all *except* one item in python

256,552

Solution 1

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

a = range(10)[::-1]                       # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
b = [x for i,x in enumerate(a) if i!=3]   # [9, 8, 7, 5, 4, 3, 2, 1, 0]

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:

a = range(10)[::-1]     # a = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
a.pop(3)                # a = [9, 8, 7, 5, 4, 3, 2, 1, 0]

In numpy you could do this with a boolean indexing:

a = np.arange(9, -1, -1)     # a = array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
b = a[np.arange(len(a))!=3]  # b = array([9, 8, 7, 5, 4, 3, 2, 1, 0])

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

Solution 2

The simplest way I found was:

mylist[:x] + mylist[x+1:]

that will produce your mylist without the element at index x.

Example

mylist = [0, 1, 2, 3, 4, 5]
x = 3
mylist[:x] + mylist[x+1:]

Result produced

mylist = [0, 1, 2, 4, 5]

Solution 3

>>> l = range(1,10)
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l[:2] 
[1, 2]
>>> l[3:]
[4, 5, 6, 7, 8, 9]
>>> l[:2] + l[3:]
[1, 2, 4, 5, 6, 7, 8, 9]
>>> 

See also

Explain Python's slice notation

Solution 4

If you are using numpy, the closest, I can think of is using a mask

>>> import numpy as np
>>> arr = np.arange(1,10)
>>> mask = np.ones(arr.shape,dtype=bool)
>>> mask[5]=0
>>> arr[mask]
array([1, 2, 3, 4, 5, 7, 8, 9])

Something similar can be achieved using itertools without numpy

>>> from itertools import compress
>>> arr = range(1,10)
>>> mask = [1]*len(arr)
>>> mask[5]=0
>>> list(compress(arr,mask))
[1, 2, 3, 4, 5, 7, 8, 9]

Solution 5

Use np.delete ! It does not actually delete anything inplace

In your example, "mylist[~3]" would be written like that: mylist.delete(3)

A more complex example:

import numpy as np
a = np.array([[1,4],[5,7],[3,1]])                                       
 
# a: array([[1, 4],
#           [5, 7],
#           [3, 1]])

ind = np.array([0,1])                                                   

# ind: array([0, 1])

# a[ind]: array([[1, 4],
#                [5, 7]])

all_except_index = np.delete(a, ind, axis=0)                                              
# all_except_index: array([[3, 1]])

# a: (still the same): array([[1, 4],
#                             [5, 7],
#                             [3, 1]])
Share:
256,552

Related videos on Youtube

choldgraf
Author by

choldgraf

Updated on January 13, 2022

Comments

  • choldgraf
    choldgraf over 2 years

    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

  • DSM
    DSM over 10 years
    I might use something like np.arange(len(arr)) != 3 as the mask, because then it can be inlined, e.g. arr[~(np.arange(len(arr)) == 3)] or whatever.
  • Abhijit
    Abhijit over 10 years
    @DSM: Please post this as an answer :-). Any case, I am not quite conversant with Numpy.
  • Bi Rico
    Bi Rico over 10 years
    +1 for masking an array, in the case of a list I would go with slice and concatenate over using compress.
  • Bi Rico
    Bi Rico over 10 years
    Good answer for a list. You could use it for arrays too but you'd need to use numpy.concatenate.
  • Jack TC
    Jack TC about 9 years
    I found this actually remove the item x+1, still useful though, thanks
  • theonlygusti
    theonlygusti over 3 years
    @JackTC it shouldn't
  • Qbik
    Qbik about 3 years
    Python seems to be somehow outdated in case of basic operations
  • jfaleiro
    jfaleiro about 3 years
    exc = lambda s, i: s[:i] + s[i+1:] exc(mylist, 3) [0, 1, 2, 4, 5]
  • Gustin
    Gustin about 2 years
    if x==5, it will not raise an IndexError. In Python, list slicing out of bounds does not result in an error, because when the start/end indices of the slice are greater than the length of the list, then they are simply reduced to the length of the list. Source: Python Docs note 4
  • pan0ramic
    pan0ramic about 2 years
    Ah! filterfalse is a great solution here (and my vote for the best non-numpy solution). Thanks!