Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a list of values remove first occurrence

def drop dest(routes,location):
    for i in range(len(routes)):
        if routes[i] == location:
              routes.remove(routes[i])
    return routes

I am using a function definition given a list as
routes = [(3,2),(2,4),(5,5),(2,4)], and say I just want to remove the first occurrence value of (2,4). I am a little confused in how to do this because I do remove the value but I also remove the other value given. Where I just want to remove the first given value.

like image 261
brian012 Avatar asked Apr 30 '16 17:04

brian012


People also ask

How do you remove the first occurrence in Python?

Using a Loop to remove the first occurrence of character in String. Create an empty string to store our result and a flag set to False to determine whether we have encountered the character that we want to remove. Iterate through each character in the original string.

How do you remove one item from a list in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.

How do you get rid of the first element?

shift() The shift() method removes the first element from an array and returns that removed element.


Video Answer


1 Answers

It's simple, use list.remove.

>>> routes = [(3,2),(2,4),(5,5),(2,4)]
>>> routes.remove((2,4))
>>> routes
[(3, 2), (5, 5), (2, 4)]
like image 84
timgeb Avatar answered Oct 07 '22 15:10

timgeb