0

I want to delete elements from list of tuple with given index values.

Input: [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]

Task to be done:
delete item at given index: 2,3

Desired output: [(1, 2), (3, 4), (9, 10)]

I have tried following code for it:

list(numpy.delete(input, [3,2]))  

But I got following output: [1, 2, 5, 6, 7, 8, 9, 10]

Kindly suggest me possible ways to solve this case.

Shweta
  • 1,111
  • 3
  • 15
  • 30

3 Answers3

3

list.pop() will remove selected elements. they have to be done in reverse order so as not to modify the position of the later ones.

list.pop(3)
list.pop(2)
rbp
  • 1,850
  • 15
  • 28
Vamoos
  • 327
  • 4
  • 10
1

you can use del:

del mylist[index]
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
0

numpy: specify the axis for multidimensional arrays

What you did with numpy was close but you used the wrong axis. If you specify axis=0 you get the result you wanted.

>>> import numpy as np
>>> l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]  
>>> l = np.array(l)
>>> l
array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10]])
>>> np.delete(l, [2,3], axis=0)
array([[ 1,  2],
       [ 3,  4],
       [ 9, 10]])

Vanilla Python

For operations that mutate the list step by step, it's important to go by descending order of the indices so e.g. [3, 2] instead of [2, 3]:

With pop()

>>> l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]  
>>> l.pop(3)
(7, 8)
>>> l.pop(2)
(5, 6)
>>> l
[(1, 2), (3, 4), (9, 10)]

With del

>>> l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]  
>>> for i in [3, 2]:
...     del l[i]
... 
>>> l
[(1, 2), (3, 4), (9, 10)]

With remove()

>>> l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]  
>>> remove_list = [l[2], l[3]]
>>> remove_list
[(5, 6), (7, 8)]
>>> for r in remove_list:
...     l.remove(r)
... 
>>> l
[(1, 2), (3, 4), (9, 10)]
bakkal
  • 54,350
  • 12
  • 131
  • 107