Given a list of values remove first occurrence

17,191

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)]
Share:
17,191
brian012
Author by

brian012

Updated on July 24, 2022

Comments

  • brian012
    brian012 almost 2 years
    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.

  • brian012
    brian012 about 8 years
    I understand that but using my code with the for loop, because my code removes all the value that match it. How do you I fix my code to just remove the first value
  • timgeb
    timgeb about 8 years
    @brian012 because your for loop keeps going after the first removal. You could add a break to the if block.