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
10
  • Please update your question with the code you have tried. Commented Nov 23, 2020 at 16:06
  • Are the elements in removelistst distinct? Commented Nov 23, 2020 at 16:07
  • Can't you just do removelistst.remove(value + str(index))? Commented Nov 23, 2020 at 16:08
  • @quamrana I just did, thanks Commented Nov 23, 2020 at 16:11
  • @Barmar Yes, they are Commented Nov 23, 2020 at 16:12

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I tried it out without sorting to observe the problem.
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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.