0

I have two lists:

A = ['PA', 'AT', 'TR']
removlistv = ['TR', 'AI', 'IO', 'SO', 'CR', 'PH', 'RT']

I find the intersection of the two lists:

rm_nodes = set(A) & set(removelistv)

Which creates the set {'TR'}. I now want to find the index of that intersection (or intersections) in the list removelistv:

indices = [removelistv.index(x) for x in rm_nodes]

So far so good, indices contains the correct value. The problem starts when I want to use the index value (which in this case is [0] i.e. a list) to retrieve the matching item in a third list removelistst = ['TR0', 'AI1', 'IO1', 'SO0', 'CR1', 'PH0', 'RT1']. My goal is to remove the item 'TR0' from removelistst. Basically, I want to remove items from this list based on the output of the intersection of the two lists in the beginning.

I've tried the following:

numbers =[ int(x) for x in indices ]
removelistst[numbers]

Which returns the error:

TypeError: list indices must be integers or slices, not list
jonna_983
  • 79
  • 1
  • 6

2 Answers2

4

Loop through indices and pop the specified element out of removelistst.

for index in sorted(indices, reverse=True):
    removelistst.pop(index)

I sort indices in reverse so that removing an element won't affect the indexes of later elements to be removed.

Barmar
  • 741,623
  • 53
  • 500
  • 612
2

There's lots of ways to do this, here's a list comprehension:

removelistst = [value for index, value in enumerate(removelistst) if index not in numbers]
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173