I'm trying to understand what the following function does, and in specific what does the if
part is doing:
def remove(items, value):
new_items = []
found = False
for item in items:
if not found and item == value:
found = True
continue
new_items.append(item)
if not found :
raise ValueError('list.remove(x): x not in list')
return new_items
The statement if not found and item == value:
and the trick of variable found
. can someone specifically explain it?
Thanks, Now I understand the example code snippet above. And I can write code to implement my idea
My idea is to first make sure the value is in the initial list . then compare every item with that value, add the item which doesn't satisfy condition item != value to a new list new_items, finally return the new list.
def remove(items, value):
new_items = []
for item in items:
if item == value :
continue
else :
new_items.append(item)
if len(items) == len(new_items):
print("This value is not in the list")
return new_items