Removing first occurence

https://app.dataquest.io/m/1018/lists/16/removing-the-first-occurrence

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

1 Like

Hi @piya,

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')

Best,
Sahil

April 2020 and you remove apple instead of bat? Evil!

1 Like