2

I have a list of items like so:

A = [[0 A B],[1 C D],[2 E F],[3 G H],[4 I L],[5 M N],[6 O P],[7 Q R],[8 S T],[9 U Z]]

I then define another list like so:

index = [0,2,6]

My goal is to remove the lists 1, 3 and 7 from A so that the result is:

A = [[1 C D],[3 G H],[4 I L],[5 M N],[7 Q R],[8 S T],[9 U Z]]

What is the smartest way to remove such items? If possible I would like to make it without using for loops.

I tried to use the following code but obviously it does not work since the size of A is affected at every iteration

for j in index:
    del A[j]
Federico Gentile
  • 5,650
  • 10
  • 47
  • 102

4 Answers4

7

Probably the most functional (and Pythonic) way would be to create a new list, omitting the elements at those indices in the original list:

def remove_by_indices(iter, idxs):
    return [e for i, e in enumerate(iter) if i not in idxs]

See it in action here.

erip
  • 16,374
  • 11
  • 66
  • 121
2

I simple trick would be to remove them from end to start, so the position of deletion is not affected

for j in sorted(index, reverse=True):
    del A[j]
blue_note
  • 27,712
  • 9
  • 72
  • 90
2

Use a list comprehension and enumerate to create a new list:

A = [['0 A B'],['1 C D'],['2 E F'],['3 G H'],['4 I L'],['5 M N'],['6 O P'],['7 Q R'],['8 S T'],['9 U Z']]

print([element for index, element in enumerate(A) if index not in (0, 2, 6)])
>> [['1 C D'], ['3 G H'], ['4 I L'], ['5 M N'], ['7 Q R'], ['8 S T'], ['9 U Z']]
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
2

Or, use a list comprehension to make a new list that has the properties you want, then immediately replace the old list.

A = [i for i in A if i[0] not in [0, 2, 6]]
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96