python remove from list see which value caused the error

You don’t actually have to do anything fancy for a list (well, except use list comprehension, which is pretty darn fancy). Here it is:

list = ['war', 'peace', 'prisons', 'parks', 'hate', 'love']
remove = ['war', 'police', 'prisons', 'hate']
left = [i for i in list if i not in remove]

With the result:

>>> left
['peace', 'parks', 'love']

I was actually trying to do this with dictionaries and that or something else about the situation made it a bit harder, so here is the notes for that.

I couldn’t find a way to do a try / except that would tell me what item actually caused it when doing list comprehension, so went with two steps:

    # Add any never-before-recorded roles for safe iterating below.
    [participation.setdefault(role, []) for role in roles if role not in participation]
    # A participation dict looks like this (two roles each with two people):
    # {'janitor': [('Tommy', 2), ('Fran', 4)], 'bookkeeper': [('Jane', 3), ('Sam', 1)]}
    # We don't care about the second number, keeping track of how many times
    # a person has served, right now, so we extract the people who have
    # served at all in a given role as a simple list.
    served = [i[0] for i in participation[role]]

Works the same with nested dictionaries:

# Add any never-before-recorded roles for safe iterating below.
  [participation.setdefault(role, []) for role in roles if role not in participation]
  # A participation dict looks like this (two roles each with two people):
  # {'janitor': {'Tom': 2, 'Fran': 4}, 'bookkeeper': {'Jane': 3, 'Sam': 1}}
  # We don't care about the second number, keeping track of how many times
  # a person has served, right now, so we extract the people who have
  # served at all in a given role as a simple list.
  served = [i for i in participation[role].keys()]

This is from https://gitlab.com/pwgd/talk-by-lot/blob/main/talkbylot/roles.py