Items in list is not removed accordingly [duplicate]
Clash Royale CLAN TAG#URR8PPP
Items in list is not removed accordingly [duplicate]
This question already has an answer here:
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:
endswith
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.
.remove()
del
.pop()
['toyBody:leg_ctrl']
Could someone kindly advise?
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
main_ctrls
for
You are changing the list while iterating over it. Not a good idea
– RafaelC
Aug 7 at 19:47
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 7 at 19:47
Sorry, it was an error on my part, have since made the relevant change
– dissidia
Aug 7 at 19:48
Quick fix would be using
enumerate(toy_ctrls[:])
and remove
.– RafaelC
Aug 7 at 19:49
enumerate(toy_ctrls[:])
remove
For one, you never use
main_ctrls
in yourfor
loop.– W Stokvis
Aug 7 at 19:45