python - I'm trying to learn why I can't seem to delete every index in a list with a loop -
this question has answer here:
i'm not sure why list not deleting every char indexed based on second list. below code:
l1 = ['e', 'i', 'l', 'n', 's', 't'] l2 = ['e', 'i', 'l', 'n', 's', 't'] n_item in range(len(l1)): if l1[n_item] in l2: del l2[n_item] below error i'm getting:
traceback (most recent call last): file "<pyshell#241>", line 3, in <module> del l2[n_item] indexerror: list assignment index out of range thanks ....
as remove earlier items, list becomes shorter, later indicies don't exist. symptom of iterating index in python - terrible idea. it's not how python designed , make unreadable, slow, inflexible code.
instead, use list comprehension construct new list:
[item item in l1 if item not in l2] note if l2 large, might worth making set first, membership tests on set quicker.
Comments
Post a Comment