Federico Gentile Federico Gentile - 1 year ago 69
Python Question

Remove items from list according to a list of indexes

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]

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download