def remove_first(list1,obj):
for i in range(len(list1)):
if list1[i]==obj:
list1=list1[:i]+list1[i+1:]
return list1
remove_first(['apple','bat','crow','daisy','potato','apple'],'apple')
Problem:
How do I ensure loop ends once list1[I]==obj. The code above does not stop the for loop once the list1[i]==obj
You can use the break statement to terminate the for loop like this:
def remove_first(list1,obj):
for i in range(len(list1)):
if list1[i]==obj:
list1=list1[:i]+list1[i+1:]
break
return list1
remove_first(['apple','bat','crow','daisy','potato','apple'],'apple')
However, even though it looks like it is working, the solution is not modifying the original list object.
list1=list1[:i]+list1[i+1:] is creating a new list object. As a workaround, you can use list1[:] like this:
list1[:]=list1[:i]+list1[i+1:]
By the way, a cleaner way to solve this problem is to follow the Dataquest’s approach of using list_object.remove(element) or alternatively, we can use del keyword like this:
def remove_first(list1,obj):
for i in range(len(list1)):
if list1[i]==obj:
del list1[i]
return list1
remove_first(['apple','bat','crow','daisy','potato','apple'],'apple')