0

I am trying to remove items within a list based on the list of items from another list (in which the items within are slightly different). It is like a "wildcard" search in which I end up using endswith to check as follows:

main_ctrls = [
        "main_start_ctrl",
        "main_global_ctrl",
        "main_local_ctrl",
        "main_path_ctrl"
    ]

toy_ctrls = ['toyBody:main_start_ctrl', 'toyBody:main_global_ctrl', 'toyBody:leg_ctrl', 'toyBody:main_local_ctrl', 'toyBody:main_path_ctrl']

for index, ctrl in enumerate(toy_ctrls):
    if ctrl.endswith(tuple(main_ctrls)):
        #toy_ctrls.remove(ctrl)
        # del toy_ctrls[index]
        # toy_ctrls.pop(index)

print toy_ctrls 
# Returns : ['toyBody:base_global_ctrl', 'toyBody:base_path_ctrl', 'toyBody:leg_ctrl']

However, as seen in the above code, I have tried .remove(), del, .pop() and it returns the same output (3 items in the list) instead of the 1 item - ['toyBody:leg_ctrl'] that I am expecting.

Could someone kindly advise?

dissidia
  • 1,531
  • 3
  • 23
  • 53
  • For one, you never use `main_ctrls` in your `for` loop. – W Stokvis Aug 07 '18 at 19:45
  • 1
    You are changing the list while iterating over it. Not a good idea – rafaelc Aug 07 '18 at 19:47
  • 4
    You can't remove elements from a list while iterating over it. Usually you want to just build up a new list with the values you want to keep. Sometimes you want to iterate over a copy, or iterate backward, or build up a list of indices and delete them in reverse order, or other things, but usually just making a copy is simpler. – abarnert Aug 07 '18 at 19:47
  • Sorry, it was an error on my part, have since made the relevant change – dissidia Aug 07 '18 at 19:48
  • Quick fix would be using `enumerate(toy_ctrls[:])` and `remove`. – rafaelc Aug 07 '18 at 19:49
  • @RafaelC At least `del` is better than `remove`, but it's still not a great idea. – abarnert Aug 07 '18 at 19:51
  • Anyway, this is a dup of an existing question that already has good answers; just let me find it. – abarnert Aug 07 '18 at 19:51
  • @abarnert definetely – rafaelc Aug 07 '18 at 19:51
  • We actually have three separate canonical questions on this one, because the other two have answers that cover less common but occasionally needed cases (e.g., you have to remove in-place, and have to go in forward order, so you need to use a `while` loop with tricky increment logic), but you probably only need to read the first one. – abarnert Aug 07 '18 at 19:54
  • @abarnert You are right. I had thought I will be able to do all these - list comprehension plus removing of list items all at one go. Now having created another list to append the results of `.endswith` and removing them from `toy_ctrls` works now – dissidia Aug 07 '18 at 20:07

0 Answers0